我是 JUnit 测试的新手。我无法编写成功的测试用例,我创建的测试用例返回空指针异常

Posted

技术标签:

【中文标题】我是 JUnit 测试的新手。我无法编写成功的测试用例,我创建的测试用例返回空指针异常【英文标题】:I am new to JUnit Testing.I am unable to write successful test cases and the test Case I create is returning a nullpointer exception 【发布时间】:2017-05-24 05:37:21 【问题描述】:

我正在尝试为以下控制器的端点控制器编写测试用例

@RestController
@RequestMapping("/agent/")
public class AgentRestController extends BaseRestController 

    @RequestMapping(value = "/log/revisionId/", method = RequestMethod.PUT)
    public ResponseEntity<?> log(@PathVariable("revisionId") String revisionId, @RequestBody LogMessage message) 

        ConfigurationRevision cr = configurationRevisionRepository.findOne(revisionId);
        BackupLog log = new BackupLog(message);
        log.setRevision(cr);
        backupLogRepository.save(log);

        return new ResponseEntity<>(HttpStatus.CREATED);
    

    @RequestMapping("/config")
    @ResponseBody
    public AgentConfig getConfiguration(HttpServletRequest request) 
        AgentConfig cfg = getAgentConfigByIP(request.getRemoteAddr());
        LogMessage log = new LogMessage();
        log.level = LogLevel.INFO;
        log.date = System.currentTimeMillis();
        log.msg = "SYSTEM: Configuration retrieved by client";

        // log the configuration retrieval
        log(cfg.id, log);
        return cfg;
    


我正在尝试为这些控制器编写 Junit 测试用例

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes =  Application.class )
@WebAppConfiguration
public class ApiControllerTest 

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setup() throws Exception 
        this.mockMvc = webAppContextSetup(webApplicationContext).build();
    

    @Test
    public void getConfigurationSuccess() throws Exception 

        mockMvc.perform(get("/agent/config").accept(MediaType.APPLICATION_JSON)).andExpect(status().is2xxSuccessful());

    


这是堆栈跟踪

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:980)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:859)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    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:155)
    at backup.itests.ServiceTest.getConfigurationSuccess(ServiceTest.java:43)
    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: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.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:254)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    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:193)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.NullPointerException
    at backup.restservice.BaseRestController.getAgentConfigByIP(BaseRestController.java:25)
    at backup.restservice.AgentRestController.getConfiguration(AgentRestController.java:34)
    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:136)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
    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:968)
    ... 39 more

谁能帮我为给定的两个控制器编写 JUnit 或 JBehave 测试用例,并为 AgenRestController 中的控制器扩展测试用例。这将是一个伟大的建设性帮助。

【问题讨论】:

我没有看到 NPE;我看到一个 ConnectException:连接被拒绝。看起来您拥有的任何数据库配置都失败了。 连接数据库时。然后它给出 NPE。 这不是你的问题中的错误。 能否请您提出建议。如何编写控制器的测试用例 您说您获得了 NPE。您还没有向我们展示与 NPE 关联的堆栈跟踪。如果没有适当的信息,我们将如何提供帮助? 【参考方案1】:
private WebApplicationContext webApplicationContext;

@Before
public void setup() throws Exception 
    this.mockMvc = webAppContextSetup(webApplicationContext).build();

这里只是在黑暗中拍摄,但 webApplicationContext 为空,并且未初始化。也许在 this.mockMcx = ... 之前,您可以插入以下行:

webApplicationContext = new WebApplicationContext();

【讨论】:

以上是关于我是 JUnit 测试的新手。我无法编写成功的测试用例,我创建的测试用例返回空指针异常的主要内容,如果未能解决你的问题,请参考以下文章

如何为 Spring 托管 bean 编写 Junit 测试用例?

如何在junit中编写字符串数组输入的测试用例?(junit的新增内容)

我的方法的 JUnit 测试

如何为调用 API 的方法编写 JUnit 测试?

如何使用 mockito 为以下代码编写 junit 测试?

为啥使用 JUnit 进行测试?