我正在与:


春季MVC
春季休息
春季MVC测试


用于在以下位置生成数据:


XML格式
JSON格式
的HTML


我有这个课:

@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();
    }

}


我需要XML的包装类。可以在JSON中和平使用它。

@Controller具有(观察集合的创建方式):

@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());
    }


XML / JSON的@RequestMapping

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


考虑以上休息,因为它使用@ResponseBody

通过Spring MVC测试和Hamcrest

我可以分别检查XML和JSON的内容,如下所示:

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")))
 ….




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")))
….


我的问题是Spring MVC。在另一个@Controller方法下面的同一@RequestMapping中:

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


它返回视图名称并使用模型。在Spring MVC中有多常见

感谢Spring MVC Test print()方法,我可以确认以下内容:

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 = []


仔细查看:


value数据
记住GenericCollection<T>toString()方法。


为了测试,我有:

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


直到那里工作。因此,已返回一些数据而不是null。

如何查看大小和数据?

我尝试过的大小:

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


我得到

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]….]


如果我用

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


我总是

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]]


那么正确的语法是什么。

最佳答案

因为您试图为包装在GenericConnection类中的Collection编写断言,所以您需要首先获取对实际Collection的引用,然后才能为其编写断言。这应该可以解决问题:

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


检查内容的方法如下:

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

                                )
                             )
                           )
                         )
                     )

关于xpath - Hamcrest的Spring MVC测试:通用集合的测试大小和值(value),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34473750/

10-12 00:23
查看更多