使用 Hamcrest 进行 Spring MVC 测试 : how count and test the properties number/size of an object inside a Model

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

对于 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))))

最佳答案

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/

相关文章:

java - 如何为 MockMvcRequestBuilders 构建获取查询字符串?

java.lang.AssertionError : Content type not set

java - 使用静态导入时如何提示类型推断?

java - 断言 JMockit 期望结果与构造的实例相同

spring - 运行 maven 时禁止 Jasper 库下载 : mvn package

Spring MVC 测试 3.2.2 由于某些奇怪的原因失败 "flash().attributeExists"断言

spring - 如何从intellij idea在Tomcat上部署war(spring app)?

java - 无法加载ApplicationContext(Spring Boot)

junit - 如何使用 junit 的 assertThat 检查列表是否仅包含某些不相关的类类型?

spring - 为什么 spring @schedule 不能与 @Lazy 一起使用