控制器单元测试时发生意外错误

时间:2019-05-13 08:56:07

标签: rest unit-testing spring-boot junit

我正在学习单元测试。我已经在示例项目中为spring boot controller实施了单元测试。当我运行测试类时,每次返回400状态(预期为200)。经过研究后,我发现if(entity.getStatusCode().equals(HttpStatus.OK)) {是给出例外的行。可能是因为它使用了Service2的返回。

但是,代码可以正常运行,而无需运行测试用例。我已经附加了MyController和MyControllerTest类。

我的控制器

@RestController
@RequestMapping("/user")
public class UserController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
@Autowired
private UserManagementService userManageService;
@Autowired
private AdminManagementService adminManageService;
@Autowired
private AuthenticateManagementService authService;

@PutMapping("/change-password")
public ResponseEntity<?> changePassword(@RequestHeader("Authorization") String token, 
        @RequestBody PasswordChangeRequestDTO passwordChangeRequestDTO) {
    ResponseDTO finalResponse = new ResponseDTO();
    try {
        LOGGER.info("Changing user password.");
        KeycloakLoginResponseDTO keycloakResponse = authService.auhtenticate(passwordChangeRequestDTO.getLoginRequestDTO());
        ResponseEntity<?> logoutEntity = authService.logout(token, keycloakResponse.getSession_state());
        if(logoutEntity.getStatusCode().equals(HttpStatus.OK)) {
            LOGGER.info("User password matched");
        }
        String userId = adminManageService.getUserByName(token, passwordChangeRequestDTO.getLoginRequestDTO().getUsername());
        ResponseEntity<?> entity = userManageService.changePassword(token, passwordChangeRequestDTO, userId);
        LOGGER.info("USER : " + "" +"has successfully changed password.");
        finalResponse.setMessageCode(HttpStatus.OK);
        finalResponse.setMessage("Password changed successfully");
        finalResponse.setError(false);
        ResponseEntity<ResponseDTO> finalEntity = ResponseEntity.ok().body(finalResponse);
        return finalEntity;
    }catch (Exception e) {
        e.printStackTrace();
        LOGGER.error("Error has occured while changing password of USER : " + "" + ".");
        finalResponse.setMessageCode(HttpStatus.EXPECTATION_FAILED);
        finalResponse.setMessage("Oops! Looks like you have entered the wrong password in the 'Old Password' field");
        finalResponse.setMessageDetail(e.getMessage());
        finalResponse.setError(true);
        ResponseEntity<ResponseDTO> finalEntity = ResponseEntity.badRequest().body(finalResponse);
        return finalEntity;
    }
}
}

控制器单元测试类

@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private UserManagementService userManageService;
@MockBean
private AdminManagementService adminManageService;
@MockBean
private AuthenticateManagementService authService;

@InjectMocks
private UserController userController;

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
}

@Test
public void testChangePasswordhappyPath() throws Exception {
    PasswordChangeRequestDTO passwordChangeRequestDTO = new PasswordChangeRequestDTO();
    LoginRequestDTO loginRequestDTO = new LoginRequestDTO();
    loginRequestDTO.setClient_id("test_client");
    loginRequestDTO.setGrant_type("test_grant_type");
    loginRequestDTO.setPassword("test_password");
    loginRequestDTO.setUsername("test_user");
    CredentialsRequestDTO credentialsRequestDTO = new CredentialsRequestDTO();
    credentialsRequestDTO.setTemporary(false);
    credentialsRequestDTO.setType("password");
    credentialsRequestDTO.setValue("test_password");
    passwordChangeRequestDTO.setLoginRequestDTO(loginRequestDTO);
    passwordChangeRequestDTO.setCredentialsRequestDTO(credentialsRequestDTO);

    ResponseEntity<String> mockResponse = new ResponseEntity<String>("", HttpStatus.OK);
    when(userManageService.changePassword("Token", passwordChangeRequestDTO, "UserId")).thenReturn(mockResponse);
    ObjectMapper objectMapper = new ObjectMapper();
    String json = objectMapper.writeValueAsString(passwordChangeRequestDTO);

    mockMvc.perform(put("/user/change-password", passwordChangeRequestDTO)
            .accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_JSON)
            .header("Authorization", "Token")
            .content(json)
            .characterEncoding("utf-8"))
        .andExpect(status().isOk()).andReturn();
}
}

我在这里做错了什么。有什么可以添加到我的MyControllerTest类中的,或者如何覆盖这个测试用例。任何帮助将不胜感激。

已更新

我还添加了e.printStackTrace()

java.lang.NullPointerException
at com.mycode.controller.UserController.changePassword(UserController.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:919)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:182)
at com.mycode.controller.UserControllerTest.testChangePasswordhappyPath(UserControllerTest.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

0 个答案:

没有答案