【问题标题】:Spring MVC Test with Hamcrest: How test size and value for a Generic Collection使用 Hamcrest 进行 Spring MVC 测试:如何测试通用集合的大小和值
【发布时间】:2016-04-01 03:15:33
【问题描述】:

我正在与:

  • Spring MVC
  • 弹簧架
  • Spring 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;
}

考虑上面的Rest,因为它使用@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。在 same @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&lt;T&gt;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]]

那么正确的语法是什么。

【问题讨论】:

    标签: xpath junit hamcrest jsonpath spring-test-mvc


    【解决方案1】:

    因为您尝试为包装在 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"))
    
                                    )
                                 )
                               )
                             )
                         )
    

    【讨论】:

      猜你喜欢
      • 2017-01-14
      • 2017-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-06
      • 2022-11-24
      • 1970-01-01
      • 2019-08-17
      相关资源
      最近更新 更多