2013-04-30 62 views
0

我有一個Spring MVC 3.2項目,我想單元&集成測試。問題是我擁有的所有依賴關係,即使使用Sprint測試,測試也非常困難。集成測試春季mvc最好的方法

我有一個這樣的控制器:

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

這將返回一個JSON對象。我想測試這個調用返回一個200和罐頭JSON的正確對象。但是,我有很多這些@Autowired類調用其他類的,即使我嘲笑他們是這樣的:

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

這創造了很多嘲笑類。下面是我想測試一下:

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

} 

我可以走通,並設置一個H2 embeddeddatabase和填充它,但我不知道這是否真的是這個控制器或應用程序的測試?任何人都可以推薦一些更好的方法來進行這種集成測試嗎如何爲控制器編寫單元測試?

謝謝!

回答