Spring 使用弹簧&x27;在MockMvc框架中,如何测试模型属性的属性值?

Spring 使用弹簧&x27;在MockMvc框架中,如何测试模型属性的属性值?,spring,junit,model,mockmvc,Spring,Junit,Model,Mockmvc,我正在使用Spring3.2.11.RELEASE和JUnit4.11。我正在使用Spring的org.springframework.test.web.servlet.MockMvc框架来测试控制器方法。在一个测试中,我有一个填充了以下对象的模型: public class MyObjectForm { private List<MyObject> myobjects; public List<MyObject> getMyObjects() {

我正在使用Spring3.2.11.RELEASE和JUnit4.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;
    }

}
使用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"));

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

如果对象具有getter
getMyProperty
,则可以嵌套
hasItem
hasProperty
匹配器

.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)))));

以防其他人遇到这个问题。我在测试列表中的类(Customer)的属性(firstName)的值时遇到了类似的问题。以下是对我有效的方法:

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

您确定“MyObject[0]”是指向模型数组第一项的正确方式吗?当我实现您的解决方案时,我得到错误'java.lang.AssertionError:Model属性'MyObjectForm'应为:hasProperty(“myObjects[0]”,一个包含hasProperty(“myProperty”)的集合,但:没有属性“myObjects[0]”。我已经验证了我的模型实际上至少有一个项的数组。你能在模型中添加代码将MyObjectForm实例放入其中吗?
.andExpect(model().attribute("customerList", Matchers.hasItemInArray(Matchers.<Customer> hasProperty("firstName", Matchers.equalToIgnoringCase("Jean-Luc")))))