7

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?

Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72
Dave
  • 15,639
  • 133
  • 442
  • 830

2 Answers2

13

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)))));
Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72
  • Are you sure that "myObjects[0]" is the right way to the first item of the model's array? When I implement your solution I get the error 'java.lang.AssertionError: Model attribute 'MyObjectForm' Expected: hasProperty("myObjects[0]", a collection containing hasProperty("myProperty", )) but: No property "myObjects[0]"'. I have verified that my model does in fact have an array of at least one item. – Dave Jan 19 '16 at 17:48
2

In case anyone else comes across this problem. I ran into a similar issue trying to test a value of an attribute (firstName), of a class (Customer) in a List< Customer >. Here is what worked for me:

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