Java 如何在使用JUnit和MockMVC时测试model属性的属性不为null?
在下面的JUnit测试中,我正在验证模型属性是否存在、是否具有特定类型和特定属性:Java 如何在使用JUnit和MockMVC时测试model属性的属性不为null?,java,spring-mvc,junit,hamcrest,Java,Spring Mvc,Junit,Hamcrest,在下面的JUnit测试中,我正在验证模型属性是否存在、是否具有特定类型和特定属性: @Test public void myTest() throws Exception { mockMvc.perform(get(MY_URL)) .andExpect(status().is2xxSuccessful()) .andExpect(view().name(MY_VIEW_NAME)) .andExpect(model
@Test
public void myTest() throws Exception {
mockMvc.perform(get(MY_URL))
.andExpect(status().is2xxSuccessful())
.andExpect(view().name(MY_VIEW_NAME))
.andExpect(model().attribute("myForm", instanceOf(MyForm.class)))
.andExpect(model().attribute("myForm", hasProperty("myProp")));
}
然后如何测试该属性是否为null?我找到了解决方案。您只需使用org.hamcrest.beans.HasPropertyWithValue.hasProperty,如下所示:
hasProperty("myProp", notNullValue()))