1

目前测试显示返回的两个对象是相同的,但断言失败。有什么方法可以比较它们吗?

 @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);
    }
4

1 回答 1

2

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

于 2018-07-04T11:55:36.043 回答