我正在尝试单元测试弹簧4.0.0 MVC应用程序。
我的控制器定义如下:
@Controller
@RequestMapping("/test")
public class TestCtrl {
@Autowired
private TestService testService;
@Autowired
private TestRessourceAssembler testRessourceAssembler;
@Autowired
private ResponseComposer responseComposer;
@RequestMapping(value = "", method = RequestMethod.GET,produces = "application/json")
public HttpEntity showAll(Pageable pageable) {
Page<Test> patr = testService.getAll(pageable);
return responseComposer.composePage(patr,testRessourceAssembler);
}
@RequestMapping(value = "/{name}", method = RequestMethod.GET)
public HttpEntity<TestRessource> show(@PathVariable String name) {
Test test = testService.getOne(name);
if(test == null){
return new ResponseEntity("Erreur !",HttpStatus.NOT_FOUND);
}
return responseComposer.compose(test,testRessourceAssembler);
}
}
我的控制器单元测试如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("test")
@WebAppConfiguration
@ContextConfiguration(classes = {ApplicationConfig.class, TestMongoConfig.class, RestConfig.class, WebMvcConfig.class})
public class TestCtrlTests{
@InjectMocks
TestCtrl testCtrl;
@Mock
TestService testService;
@Autowired
protected WebApplicationContext wac;
protected MockMvc mockMvc;
@Before
public void setup(){
MockitoAnnotations.initMocks(this);
when(testService.getOne("jexiste")).thenReturn(new com.thalesgroup.ito.c2s.mc.portail.test.domain.Test("jexiste",1990));
when(testService.getOne("plaf")).thenReturn(null);
this.mockMvc = webAppContextSetup(this.wac).build();
}
@Test
public void simpleGetAnswer() throws Exception{
assertNotNull(mockMvc);
mockMvc.perform(get("/test")).andExpect(status().isOk());
mockMvc.perform(get("/test/jexiste")).andExpect(status().isOk());
mockMvc.perform(get("/test/plaf")).andExpect(status().isNotFound());
}
}
当我运行测试时,注入并使用了"正常"测试服务bean(我可以在日志中看到跟踪),而不是模拟。
所以我在互联网上阅读了一些东西
this.mockMvc = webAppContextSetup(this.wac).build();
this.mockMvc = standaloneSetup(TestCtrl.class).build();
但是,我知道会发生这种情况,我不再这样做,所以我的pageableargumentresolver和我的其他豆(testressressourceasembler,wendessecomposers)不再注入NullPoInterException。
我的问题是:
1)我在设计错误的东西吗?
2)如果没有,我如何在将其他豆从上下文中放置在控制器中?
感谢您!
我正在研究您的测试,这应该有效。只需用模拟的豆子在控制器上构建MOCEMVC即可。之后,所有模拟都将在测试中可见。
接受
@Controller
注册的无用的无知器,从而使控制器的实例化和初始化及其依赖关系完全控制了类似于平原单元测试,并且还可以测试一个控制器一次。
不要使用春季集成测试!这是简单的单元测试!
固定测试
@RunWith(MockitoJUnitRunner.class)
public class TestCtrlTests{
@InjectMocks
TestCtrl testCtrl;
@Mock
TestService testService;
protected MockMvc mockMvc;
@Before
public void setup(){
when(testService.getOne("jexiste")).thenReturn(new com.thalesgroup.ito.c2s.mc.portail.test.domain.Test("jexiste",1990));
when(testService.getOne("plaf")).thenReturn(null);
this.mockMvc = standaloneSetup(testCtrl).build();
}
@Test
public void simpleGetAnswer() throws Exception{
assertNotNull(mockMvc);
mockMvc.perform(get("/test")).andExpect(status().isOk());
mockMvc.perform(get("/test/jexiste")).andExpect(status().isOk());
mockMvc.perform(get("/test/plaf")).andExpect(status().isNotFound());
}
}