简体   繁体   中英

java.lang.NullPointerException while testing RESTful Api with jUnit

I am trying to write a test case for following controller code using JUnit. But I am getting 500 code with null pointer Exception. (When I test this on Postman, it works without any exception.) I think HttpServeleRequest Request of validEmp might cause this null pointer exception to testGetMethod. Can any one please tell what I am doing wrong here and how to fix this? Thank you for your help:D

LoginService

public ReturnParam validEmp(HttpServletRequest request, String locale, String empKey, String accessToken) throws Exception {
    ReturnParam rp = new ReturnParam();
    rp.setFail("not available");

    return rp;
}

LoginController

@RequestMapping(value = "/valid", method = RequestMethod.GET, produces = "application/json; charset=UTF-8")
public @ResponseBody ReturnParam validEmp(HttpServletRequest request,
        @RequestParam(value = "locale", required = true) String locale,
        @RequestParam(value = "empKey", required = true) String empKey,
        @RequestParam(value = "accessToken", required = true) String accessToken) throws Exception {

    return service.validEmp(request, locale, empKey, accessToken);
}

LoginControllerTest

public MockMvc mockMvc;


private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
        MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

public void testGetMethod(String url, String locale, String empKey, String acessToken) throws Exception {
    mockMvc.perform(get(url).param("locale", locale).param("empKey",empKey).param("accessToken", acessToken))
           .andDo(print())
           .andExpect(status().isOk());
}

Console

java.lang.NullPointerException
at com.isu.ifm.hr.control.LoginController.validEmp(LoginController.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:144)
at com.isu.ifm.HttpMethodUnitTest.testGetMethod(HttpMethodUnitTest.java:21)
at com.isu.ifm.testcase.LoginControllerTest.TestCaseMain(LoginControllerTest.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
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)

MockHttpServletRequest:
         HTTP Method = GET
         Request URI = /certificate/valid
          Parameters = {locale=[ko_KR], empKey=[ISU_ST@18017], accessToken=[]}
             Headers = {}

             Handler:
                Type = com.isu.ifm.hr.control.LoginController
              Method = public com.pb.common.vo.ReturnParam com.isu.ifm.hr.control.LoginController.validEmp(javax.servlet.http.HttpServletRequest,java.lang.String,java.lang.String,java.lang.String) throws java.lang.Exception

               Async:
       Async started = false
        Async result = null

  Resolved Exception:
                Type = java.lang.NullPointerException

        ModelAndView:
           View name = jsonView
                View = null
           Attribute = status
               value = FAIL
           Attribute = message
               value = null

            FlashMap:

MockHttpServletResponse:
              Status = 500
       Error message = null
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = jsonView
      Redirected URL = null
             Cookies = []
INFO : org.springframework.context.support.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext@5abca1e0: startup date [Thu Nov 01 16:46:45 KST 2018]; root of context hierarchy
INFO : org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor - Shutting down ExecutorService 'taskExecutor'

I think problem ist not a request , but injection. According your stacktrace I would say, that service is null (injection in controller isn't working)

You need to mock your LoginService in LoginController. Try to add such code to LoginControllerTest.

@Mock
private LoginService loginService;
@InjectMocks
private LoginController loginController;
@Before
public void init(){
    MockitoAnnotations.initMocks(this);
    mockMvc = MockMvcBuilders
            .standaloneSetup(loginController)
            .build();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM