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

Is there a way to use AssertJ assertions with Spring MVC Test?

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

但我不知道如何使用 AssertJ。我在网上看到的所有示例都使用 Hamcrest 和 Spring MVC 测试。

下面是一个使用 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"))
                        )
                )));

更新

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


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

但是,您所描述的特定场景涉及 API 的 Spring MVC 测试框架。所讨论的方法旨在与 Hamcrest Matcher API 一起使用。因此无法在这些方法调用中使用 AssertJ。

此致,

Sam (Spring TestContext 框架 的作者)

最近在 Spring Boot project to discuss adding support for AssertJ assertions with MockMvc, it might be worth keeping an eye on it. You can view the issue here: https://github.com/spring-projects/spring-boot/issues/5729

上提出了一个问题

看起来 initial concept created by Phil Webb 涉及包装 MockMvc 以提供对 AssertJ 断言的支持。

我整理了一个库,它为 MockMvcResponseEntity(由 TestRestTemplate 返回)提供 AssertJ 断言:https://github.com/ngeor/yak4j-spring-test-utils