如何解决SpringMVC 单元测试 - 控制器中未调用服务方法
我正在开发 REST API,我想对控制器进行一些测试。但是当我在控制器上运行测试时,似乎没有调用服务方法。这是一个控制器,并测试了许多其他具有相同问题的控制器。
这是我要测试的控制器:
控制器
@RestController
@RequestMapping("/api/")
@CrossOrigin(origins = "*")
@Api(tags = "Auth")
public class AuthController {
@Autowired
TrainerService trainerService;
@Autowired
JwtUtil jwtUtil;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
ClientService clientService;
@ApiOperation(value = "Trainer register",response = Trainer.class)
@PostMapping("pregister")
public Trainer registerTrainer(@RequestBody Trainer trainer) throws GlobalReqException {
try {
return trainerService.register(trainer); // trainerService.register() is not called
} catch (GlobalReqException e) {
throw new GlobalReqException("Something went wrong registering trainer",e);
}
}
...
这是测试
测试
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBoottest(classes = AuthController.class)
@WebAppConfiguration
@EnableWebMvc
public class AuthControllerTest {
@MockBean
JwtUtil jwtUtil;
@MockBean
AuthenticationManager authenticationManager;
@MockBean
TrainerService trainerService;
@MockBean
ClientService clientService;
@Autowired
WebApplicationContext webApplicationContext;
protected mockmvc mvc;
@Test
@displayName("Register Trainer")
public void registerTrainer() throws Exception {
mvc = mockmvcBuilders.webAppContextSetup(webApplicationContext).build();
String json = "{\n" +
" \"userName\": \"trainer@test.com\",\n" +
" \"name\": \"trainer\",\n" +
" \"password\": \"pass12345\",\n" +
" \"phone\": \"12345678\"\n" +
"}";
String uri = "/api/pregister/";
MvcResult mvcResult = mvc.perform(mockmvcRequestBuilders.post(uri)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(json))
.andReturn();
int status = mvcResult.getResponse().getStatus();
System.out.println(mvcResult.getResponse());
assertEquals(200,status);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。