【问题标题】:Is there a way to use AssertJ assertions with Spring MVC Test?有没有办法在 Spring MVC 测试中使用 AssertJ 断言?
【发布时间】:2016-03-30 13:59:42
【问题描述】:

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

但我不知道如何使用 AssertJ。我在网上看到的所有示例都使用了带有 Spring MVC 测试的 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"))
                        )
                )));

【问题讨论】:

    标签: spring-mvc spring-test hamcrest assertj


    【解决方案1】:

    更新

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


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

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

    问候,

    Sam (Spring TestContext 框架的作者

    【讨论】:

      【解决方案2】:

      最近在Spring Boot 项目中提出了一个问题,讨论使用 MockMvc 添加对 AssertJ 断言的支持,可能值得关注。你可以在这里查看问题:https://github.com/spring-projects/spring-boot/issues/5729

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多