【问题标题】:Spring MVC Test with Hamcrest: how count and test the properties number/size of an object inside a Model使用 Hamcrest 进行 Spring MVC 测试:如何计算和测试模型内对象的属性数量/大小
【发布时间】:2017-01-14 05:29:01
【问题描述】:

对于 Spring MVC 测试(与 Java Hamcrest 一起使用):

测试需要渲染一个带有Model 对象的jsp 文件的场景,该对象只包含Person 类的一个实例,我有以下内容(工作正常):

.andExpect(model().size(1))
.andExpect(model().attributeExists("persona"))
.andExpect(model().errorCount(0))
.andExpect(model().hasNoErrors())

.andExpect(model().attribute("persona", notNullValue()))
.andExpect(model().attribute("persona", isA(Persona.class)))

.andExpect(model().attribute("persona", hasProperty("id", notNullValue())))
.andExpect(model().attribute("persona", hasProperty("id", is(persona.getId()))))
.andExpect(model().attribute("persona", hasProperty("nombre", notNullValue())))
.andExpect(model().attribute("persona", hasProperty("nombre", is(persona.getNombre()))))
.andExpect(model().attribute("persona", hasProperty("apellido", notNullValue())))
.andExpect(model().attribute("persona", hasProperty("apellido", is(persona.getApellido()))))
.andExpect(model().attribute("persona", hasProperty("fecha", notNullValue())))
.andExpect(model().attribute("persona", hasProperty("fecha", is(persona.getFecha()))));

我想知道是否可能以及如何计算 java 对象的属性/属性的数量,在本例中为 Person 类。

Person 类有新字段时,我需要这个,即:ageheight。因此,测试方法应该无法让我更新count 号码并添加

.andExpect(model().attribute("persona", hasProperty("age", notNullValue())))
.andExpect(model().attribute("persona", hasProperty("age", is(persona.getAge()))))
.andExpect(model().attribute("persona", hasProperty("height", notNullValue())))
.andExpect(model().attribute("persona", hasProperty("height", is(persona.getHeight()))));

json 中的类似

.andExpect(jsonPath("$").exists())
.andExpect(jsonPath("$.*", hasSize(is(4))))

【问题讨论】:

    标签: spring spring-test hamcrest spring-test-mvc


    【解决方案1】:
    int attrCount = model().getClass().getDeclaredFields().length;
    assertThat(attrCount, equalTo(10));
    

    【讨论】:

      猜你喜欢
      • 2017-01-21
      • 2016-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多