SpringMVC 单元测试 - 控制器中未调用服务方法

时间:2021-05-11 11:57:49

标签: java spring-boot spring-test spring-test-mvc

我正在开发 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);
    }
}

0 个答案:

没有答案