首页 > 解决方案 > 如何在 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);
    }

标签: springjunitassertionmodelandview

解决方案


我建议您编写一个真正的 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()(在静态导入的示例中)


推荐阅读