【问题标题】:Using Spring's MockMvc framework, how do I test the value of an attribute of an attribute of my model?使用 Spring 的 MockMvc 框架,如何测试我的模型属性的属性值?
【发布时间】:2016-01-18 16:32:10
【问题描述】:

我正在使用 Spring 3.2.11.RELEASE 和 JUnit 4.11。我正在使用 Spring 的 org.springframework.test.web.servlet.MockMvc 框架来测试控制器方法。在一个测试中,我有一个填充了以下对象的模型:

public class MyObjectForm 
{

    private List<MyObject> myobjects;

    public List<MyObject> getMyObjects() {
        return myobjects;
    }

    public void setMyObjects(List<MyObject> myobjects) {
        this.myobjects = myobjects;
    }

}

“MyObject”对象又具有以下字段……

public class MyObject
{
    …
    private Boolean myProperty;

使用 MockMvc 框架,如何检查“myobjects”列表中的第一项是否具有等于 true 的属性“myProperty”?到目前为止,我知道它是这样的……

    mockMvc.perform(get(“/my-path/get-page”)
            .param(“param1”, ids))
            .andExpect(status().isOk())
            .andExpect(model().attribute("MyObjectForm", hasProperty("myobjects[0].myProperty”, Matchers.equalTo(true))))
            .andExpect(view().name("assessment/upload"));

但是我不知道如何测试一个属性的属性值?

【问题讨论】:

  • 能否在将 MyObjectForm 实例放入模型的位置添加代码?

标签: spring junit model mockmvc


【解决方案1】:

如果您的对象有一个 getter getMyProperty,您可以嵌套 hasItemhasProperty 匹配器。

.andExpect(model().attribute("MyObjectForm",
   hasProperty("myObjects",
       hasItem(hasProperty("myProperty”, Matchers.equalTo(true))))))

如果您知道列表中有多少对象,则可以检查第一个项目

.andExpect(model().attribute("MyObjectForm",
   hasProperty("myObjects", contains(
         hasProperty("myProperty”, Matchers.equalTo(true)),
         any(MyObject.class),
         ...
         any(MyObject.class)))));

【讨论】:

  • 您确定“myObjects[0]”是模型数组第一项的正确方法吗?当我实施您的解决方案时,我收到错误'java.lang.AssertionError: Model attribute 'MyObjectForm' Expected: hasProperty("myObjects[0]", a collection contains hasProperty("myProperty", )) 但是:没有属性“我的对象 [0]”。我已经验证我的模型确实有一个至少包含一个项目的数组。
【解决方案2】:

以防其他人遇到此问题。我在尝试测试 List 中的类(Customer)的属性(firstName)的值时遇到了类似的问题。这对我有用:

.andExpect(model().attribute("customerList", Matchers.hasItemInArray(Matchers.<Customer> hasProperty("firstName", Matchers.equalToIgnoringCase("Jean-Luc")))))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    相关资源
    最近更新 更多