1

Currently the test shows that both objects returned are the same, but the assert fails. Is there any way to compare them?

 @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);
    }
mrkernelpanic
  • 4,268
  • 4
  • 28
  • 52
b.d
  • 53
  • 2
  • 11

1 Answers1

2

I would recommend you write a real Spring MVC Test.

E.g. like I did with spring boot

@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());

       }

}

The important thing is to check your model attributes with the org.springframework.test.web.servlet.result.ModelResultMatchers.model() method (in the example statically imported)

mrkernelpanic
  • 4,268
  • 4
  • 28
  • 52