【问题标题】:best way to integration test spring mvc集成测试spring mvc的最佳方法
【发布时间】:2013-04-23 20:55:38
【问题描述】:

我有一个 Spring MVC 3.2 项目,我想进行单元和集成测试。问题是我拥有的所有依赖项,即使使用 Sprint-test 也使测试变得非常困难。

我有一个这样的控制器:

@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 嵌入式数据库并填充它,但我想知道这是否真的是对该控制器或应用程序的测试?谁能推荐一些更好的集成测试方法?如何为控制器编写单元测试?

谢谢!

【问题讨论】:

    标签: spring-mvc spring-test integration-testing


    【解决方案1】:

    查看spring show case 项目并查看控制器测试用例,您将能够理解并了解测试控制器的标准方法。 MappingControllerTests.java 有一些基于 json 的控制器测试

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-11
      • 2012-02-17
      • 2021-09-11
      • 1970-01-01
      相关资源
      最近更新 更多