我在项目中使用 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"))
)
)));
Update
如果您想投票支持包含 AssertJ 断言MockMvc
,请参阅相关的Spring JIRA问题:SPR-16637 https://jira.spring.io/browse/SPR-16637.
一般来说,在使用 Spring 进行测试时,您可以选择任何您喜欢的断言框架。
但是,您描述的特定场景涉及 Spring MVC 测试框架的 API。所讨论的方法旨在与 Hamcrest 一起使用Matcher
API。因此不可能在这些方法调用中使用 AssertJ。
Regards,
Sam (Spring TestContext 框架的作者)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)