Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 663
Dave Avatar asked Jan 18 '16 16:01

Dave


2 Answers

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)))));
like image 81
Stefan Birkner Avatar answered Oct 02 '22 11:10

Stefan Birkner


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")))))
like image 30
Shahriar Avatar answered Oct 02 '22 11:10

Shahriar