有没有办法在Spring MVC Test中使用AssertJ断言? [英] Is there a way to use AssertJ assertions with Spring MVC Test?

查看:149
本文介绍了有没有办法在Spring MVC Test中使用AssertJ断言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been using AssertJ for some time in my projects. Recently I started using Spring MVC Test for testing Spring MVC controllers.

但是我不知道如何将AssertJ与它一起使用.我在网上看到的所有示例都使用带有Spring MVC Test的Hamcrest.

But I am not getting how to use AssertJ with it. All examples I see online all use Hamcrest with Spring MVC Test.

以下是使用Hamcrest API的示例.

Below is an example using the 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 .

If you would like to vote for inclusion of support for AssertJ assertions with MockMvc, please see the related Spring JIRA issue: SPR-16637.

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

Generally speaking, you may choose whatever assertion framework you like when testing with Spring.

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

However, the particular scenario you are describing involves the API of the Spring MVC Test framework. The methods in question are designed to be used with the Hamcrest Matcher API. It is therefore not possible to use AssertJ within those method calls.

此致

Sam (Spring TestContext Framework的作者)

这篇关于有没有办法在Spring MVC Test中使用AssertJ断言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆