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

ash*_*ram 14 spring-mvc hamcrest spring-test assertj

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

但是我没有得到如何使用AssertJ.我在网上看到的所有例子都使用Hamcrest和Spring MVC Test.

下面是使用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"))
                        )
                )));
Run Code Online (Sandbox Code Playgroud)

Sam*_*nen 13

更新

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


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

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

问候,

Sam (Spring TestContext Framework的作者)