【问题标题】:How can I compare ModelAndView objects in Junit testing?如何在 Junit 测试中比较 ModelAndView 对象?
【发布时间】:2018-12-12 15:48:04
【问题描述】:

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

 @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 junit assertion modelandview


    【解决方案1】:

    我建议你编写一个真正的 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() 方法检查您的模型属性(在示例中为静态导入)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-13
      相关资源
      最近更新 更多