Search code examples
springjunitmodelmockmvc

Using Spring's MockMvc framework, how do I test the value of an attribute of an attribute of my model?


I’m using Spring 3.2.11.RELEASE and JUnit 4.11. I’m using Spring’s org.springframework.test.web.servlet.MockMvc framework to test a controller method. In one test, I have a model that is populated with the following object:

public class MyObjectForm 
{

    private List<MyObject> myobjects;

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

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

}

The “MyObject” object in turn has the following field …

public class MyObject
{
    …
    private Boolean myProperty;

Using the MockMvc framework, how do I check that the first item in the “myobjects” list has an attribute “myProperty” equal to true? So far I know it goes something like this …

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

but I’m clueless as to how to test the value of an attribute of an attribute?


Solution

  • You can nest hasItem and hasProperty matchers if your object has a getter getMyProperty.

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

    If you know how much objects are in the list than you can check the first item with

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