spring - 如何在 Junit 测试中比较 ModelAndView 对象?
问题描述
目前测试显示返回的两个对象是相同的,但断言失败。有什么方法可以比较它们吗?
@Test
public void test_search() throws Exception {
TestObject testObject= createTestObject();
ModelAndView expectedReturn = new ModelAndView("example/test", "testForm", testObject);
expectedReturn.addObject("testForm", testObject);
ModelAndView actualReturn = testController.search(testObject);
assertEquals("Model and View objects do not match", expectedReturn, actualReturn);
}
解决方案
我建议您编写一个真正的 Spring MVC 测试。
例如,就像我对弹簧靴所做的那样
@AutoConfigureMockMvc
@SpringBootTest(classes = {YourSpringBootApplication.class})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
@RunWith(SpringRunner.class)
public class RestControllerTest {
@Autowired
private MockMvc mvc;
@org.junit.Test
public void test_search() throws Exception {
TestObject testObject= createTestObject();
mvc.perform(MockMvcRequestBuilders
.get("/yourRestEndpointUri"))
.andExpect(model().size(1))
.andExpect(model().attribute("testObject", testObject))
.andExpect(status().isOk());
}
}
重要的是使用方法检查您的模型属性org.springframework.test.web.servlet.result.ModelResultMatchers.model()
(在静态导入的示例中)
推荐阅读
- javascript - 如何在javascript中检查两个字段是否匹配?
- azure-devops - Azure DevOps 变量和多行值
- html - bootstrap4 手风琴不能通过传递索引在 ngFor 中工作
- java - 澄清:需要在我的 android 的可绘制文件夹中添加哪个图像(从 adobe xd => 它提供了 6 个不同大小的文件夹)
- assembly - 查看 x86 机器码,如何确定下一条指令的起始位置?
- asp.net - IIS - 常见文件扩展名列表(请求过滤)
- javascript - 从 Vue.js 在 HTML 页面中显示动态数据
- azure - Azure Kubernetes - 作为 AKS 设置的一部分创建的额外资源组的自定义名称?
- pytest - 我可以将 mypy 报告与 pytest 覆盖率报告结合起来吗?
- python - np.gradient 和 matlab 渐变