我有一个要测试的controller
。我将myObj添加为属性,其中myObj本身是
public class MyObj {
private List<OtherObj> otherObjList;
private SecondObj secondObj;
//getter setter
}
这是我的控制人
@Controller
public class MyController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(final Model model) {
//i prepare myobj here
model.addAttribute("myObj",myObj);
return "myPage";
}
}
这是我的测试用例。我正在尝试查看属性的第一项是否 otherObjList是否有值。这是我尝试但无法正常工作的
mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(model().attribute("myObj.otherObjList", hasItems(hasProperty("id", is(12345)))));
答案 0 :(得分:0)
当您要测试普通控制器时,我认为您的方向正确,但是.
表示法不合适。看一下以下示例测试断言:
mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(view().name("todo/list"))
.andExpect(forwardedUrl("/WEB-INF/jsp/todo/list.jsp"))
.andExpect(model().attribute("todos", hasSize(2)))
.andExpect(model().attribute("todos", hasItem(
allOf(
hasProperty("id", is(1L)),
hasProperty("description", is("Lorem ipsum")),
hasProperty("title", is("Foo"))
)
)))
.andExpect(model().attribute("todos", hasItem(
allOf(
hasProperty("id", is(2L)),
hasProperty("description", is("Lorem ipsum")),
hasProperty("title", is("Bar"))
)
)));
也许此页面可以为您提供帮助:https://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-mvc-controllers-normal-controllers/