有没有办法在Spring MVC Test中使用AssertJ断言?


问题内容

我在项目中使用AssertJ已有一段时间了。最近,我开始使用Spring MVC Test来测试Spring MVC控制器。

但是我没有得到如何与它一起使用AssertJ的信息。我在网上看到的所有示例都使用带有Spring MVC Test的Hamcrest。

以下是使用Hamcrest API的示例。

mockMvc
                .perform(get("/user?operation=userList"))
                .andExpect(status().isOk())
                .andExpect(model().attribute(UserController.MODEL_ATTRIBUTE_USER_LIST, userList))
                .andExpect(view().name(UserController.VIEW_USER_LIST))
                .andExpect(model().attribute(UserController.MODEL_ATTRIBUTE_USER_LIST, hasSize(2)))
                .andExpect(model().attribute(UserController.MODEL_ATTRIBUTE_USER_LIST, hasItem(
                        allOf(
                                hasProperty("id", is(1L)),
                                hasProperty("description", is("Lorem ipsum")),
                                hasProperty("title", is("Foo"))
                        )
                )))
                .andExpect(model().attribute(UserController.MODEL_ATTRIBUTE_USER_LIST, hasItem(
                        allOf(
                                hasProperty("id", is(2L)),
                                hasProperty("description", is("Lorem ipsum")),
                                hasProperty("title", is("Bar"))
                        )
                )));

问题答案:

更新资料

如果您想投票支持对AssertJ断言的支持MockMvc,请参阅相关的Spring
JIRA问题:SPR-16637


一般来说,在使用Spring进行测试时,您可以选择喜欢的任何断言框架。

但是,您描述的特定场景涉及Spring MVC Test框架的API。有问题的方法旨在与Hamcrest MatcherAPI
一起使用。因此,无法在这些方法调用中使用AssertJ。

问候,

Sam (Spring TestContext Framework的作者