best way to integration test spring mvc

会有一股神秘感。 提交于 2019-12-10 11:56:56

问题


I have a Spring MVC 3.2 project that I would like to unit & integration tests. The problem is all the dependencies I have, makes testing extremely difficult even with Sprint-test.

I have a controller like this:

@Controller
@RequestMapping( "/" )
public class HomeController {

    @Autowired
    MenuService menuService;  // will return JSON

    @Autowired
    OfficeService officeService; 


    @RequestMapping( method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE )
    @ResponseBody
    public AuthenticatedUser rootCall( HttpServletRequest request ) {
        AuthenticatedUser authentic = new AuthenticatedUser();

        Office office = officeService.findByURL(request.getServerName());
        authentic.setOffice(office);

        // set the user role to authorized so they can navigate the site
        menuService.updateVisitorWithMenu(authentic);
        return returnValue;
     }

This will return a JSON object. I would like to test this call returns a 200 and the correct object with canned JSON. However, I have a lot of other classes called by those @Autowired classes, and even if I mock them like this:

 @Bean public MenuRepository menuRepository() {  
      return Mockito.mock(MenuRepository.class); 
 }

this creates a lot of mocked classes. Here is how I am trying to test it:

 @RunWith( SpringJUnit4ClassRunner.class )
 @ContextConfiguration( classes = JpaTestConfig.class )
 @WebAppConfiguration
 public class HomeControllerTest {

     private EmbeddedDatabase database;

    @Resource
    private WebApplicationContext webApplicationContext;

    @Autowired
    OfficeService officeService;

    private MockMvc mockMvc;

    @Test
    public void testRoot() throws Exception {  mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
      .andExpect(content().contentType(IntegrationTestUtil.APPLICATION_JSON_UTF8))
            .andExpect(content().string(<I would like canned data here>));

}

I can go thru and setup a H2 embeddeddatabase and populate it, but I wonder if that is really a test of this controller or the application? Can anyone recommend some better approaches to this integration test? How does one write unit tests for controllers?

Thank you!


回答1:


Check out the spring show case project and take a look at controller test cases you will be able to understand and see standard way of testing controllers. MappingControllerTests.java has some json based controller testing



来源:https://stackoverflow.com/questions/16291398/best-way-to-integration-test-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!