6

我正在使用 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”对象又具有以下字段……</p>

public class MyObject
{
    …
    private Boolean myProperty;

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

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

但我对如何测试属性的属性值一无所知?

4

2 回答 2

13

如果你的对象有一个 getter ,你可以嵌套hasItem和匹配器。hasPropertygetMyProperty

.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)))));
于 2016-01-18T21:58:29.380 回答
2

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

.andExpect(model().attribute("customerList", Matchers.hasItemInArray(Matchers.<Customer> hasProperty("firstName", Matchers.equalToIgnoringCase("Jean-Luc")))))
于 2017-06-16T18:49:25.673 回答