问题描述
我有一个Spring MVC 3.2项目,我想对该项目进行&集成测试.问题是我所拥有的所有依赖关系,即使使用Sprint测试,也使测试变得极为困难.
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;
}
这将返回一个JSON对象.我想测试此调用是否返回200和带有JSON罐头的正确对象.但是,我还有很多@Autowired类调用的其他类,即使我像这样嘲笑它们也是如此:
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>));
}
我可以遍历并建立H2嵌入式数据库并进行填充,但是我想知道这是否真的是对该控制器或应用程序的测试?谁能推荐一些更好的方法来进行此集成测试?一个写单元如何测试控制器?
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?
谢谢!
推荐答案
查看春季展示柜项目,并查看控制器测试用例,您将能够了解并看到测试控制器的标准方法. MappingControllerTests.java 有一些基于json的控制器测试
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
这篇关于集成测试Spring MVC的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!