Search code examples
xpathjunithamcrestjsonpathspring-test-mvc

Spring MVC Test with Hamcrest: How test size and value for a Generic Collection


I am working with:

  • Spring MVC
  • Spring Rest
  • Spring MVC Test

it for generate data in:

  • XML
  • JSON
  • HTML

I have this class:

@XmlRootElement(name="generic-collection")
public class GenericCollection<T> {

    private Collection<T> collection;

    public GenericCollection(){

    }

    public GenericCollection(Collection<T> collection){
        this.collection = collection;
    }

    @XmlElement(name="item")
    public Collection<T> getCollection() {
        return collection;
    }

    public void setCollection(Collection<T> collection) {
        this.collection = collection;
    }

    @Override
    public String toString() {
      StringBuilder builder = new StringBuilder();
      for(Object object : collection){
        builder.append("[");
        builder.append(object.toString());
        builder.append("]");
      }
      return builder.toString();
    }

}

I need that wrap class for XML. It can be reused in peace for JSON.

The @Controller has (observe how the collection is created):

@RequestMapping(method=RequestMethod.GET, produces={MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_UTF8_VALUE})
public class PersonaFindAllController {

    private GenericCollection<Persona> personas;

    public PersonaFindAllController(){
        personas = new GenericCollection<>(PersonaFactory.crearPersonas());         
    }

The @RequestMapping for XML/JSON is

@RequestMapping(value={PersonaFindAllURLSupport.FINDALL})
public @ResponseBody GenericCollection<Persona> findAll(){
    return personas;
}

Consider above Rest since it uses @ResponseBody

Through Spring MVC Test and Hamcrest

I can check the content for XML and JSON as follows respectively:

resultActions.andExpect(xpath("generic-collection").exists())
             .andExpect(xpath("generic-collection").nodeCount(is(1)))

             .andExpect(xpath("generic-collection/item").exists())
             .andExpect(xpath("generic-collection/item").nodeCount(is(5)))

             .andExpect(xpath("generic-collection/item[1]").exists())
             .andExpect(xpath("generic-collection/item[1]/*").nodeCount(is(4)))
             .andExpect(xpath("generic-collection/item[1]/id").exists())
             .andExpect(xpath("generic-collection/item[1]/id").string(is("88")))
 ….

and

resultActions.andExpect(jsonPath('collection').exists())
             .andExpect(jsonPath('collection').isArray())

             .andExpect(jsonPath('collection',hasSize(is(5))))

             .andExpect(jsonPath('collection[0]').exists())
             .andExpect(jsonPath('collection[0].*', hasSize(is(4))))
             .andExpect(jsonPath('collection[0].id').exists())
             .andExpect(jsonPath('collection[0].id').value(is("88")))
….    

My problem is with Spring MVC. In the same @Controller below the other @RequestMapping method:

@RequestMapping(value={PersonaFindAllURLSupport.FINDALL},       produces=MediaType.TEXT_HTML_VALUE)
public String findAll(Model model){
    model.addAttribute(personas);
    return "some view";
}

It returns a view name and use a Model. It how is common in Spring MVC

Thanks to Spring MVC Test print() method I can confirm the following:

ModelAndView:
        View name = persona/findAll
             View = null
        Attribute = genericCollection
            value = [Persona [id=88, nombre=Manuel, apellido=Jordan, fecha=Mon Jul 06 00:00:00 PET 1981]][Persona [id=87, nombre=Leonardo, apellido=Jordan, fecha=Sun Jul 05 00:00:00 PET 1981]]...]
           errors = []

See carefully:

  • the value data
  • remember the GenericCollection<T>'s toString() method.

For testing I have:

resultActions.andExpect(model().attribute("genericCollection", notNullValue()))

Until there works. Therefore some data and not null has been returned.

How I can check the size and data?

I have tried for the size:

.andExpect(model().attribute("genericCollection", hasSize(5)))

And I get

java.lang.AssertionError: Model attribute 'genericCollection'
Expected: a collection with size <5>
     but: was <[Persona [id=88, nombre=Manuel, apellido=Jordan, fecha=Mon Jul 06 00:00:00 PET 1981]….]

If I use

.andExpect(model().attribute("genericCollection", hasItem("collection")))

I always

java.lang.AssertionError: Model attribute 'genericCollection'
Expected: a collection containing "collection"
     but: was <[Persona [id=88, nombre=Manuel, apellido=Jordan, fecha=Mon Jul 06 00:00:00 PET 1981]]

So what is the correct syntax.


Solution

  • Because you try to write assertion for a Collection that is wrapped inside the GenericConnection class, you need to first get a reference to the actual Collection before you can write an assertion for it. This should should do the trick:

    .andExpect(model().attribute("genericCollection", 
            hasProperty("collection", hasSize(5))
    ))
    

    To check the content is in the following way:

    .andExpect(model().attribute("genericCollection", 
                            hasProperty("collection",
                                hasItem(
                                    allOf(
                                        hasProperty("id", is("100")),
                                        hasProperty("nombre", is("Jesús")),
                                        hasProperty("apellido", is("Mão"))
    
                                    )
                                 )
                               )
                             )
                         )