对于 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
类有新字段时,我需要这个,即:age
和height
。因此,测试方法应该无法让我更新 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))))
最佳答案
int attrCount = model().getClass().getDeclaredFields().length;
assertThat(attrCount, equalTo(10));
关于使用 Hamcrest 进行 Spring MVC 测试 : how count and test the properties number/size of an object inside a Model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39354379/