vertx.createHttpServer() 抛出 NullPointerException

huangapple go评论71阅读模式
英文:

vertx.createHttpServer() throws NullPointerException

问题

我正在尝试使用 vertx 进行一些尝试性的操作。

为什么这段代码会抛出 NullPointerException?

import io.vertx.core.http.HttpServer;
import io.vertx.core.AbstractVerticle;

class vertxFacadeTest extends AbstractVerticle
{

    @Test
    void createServer()
    {
        HttpServer httpServer = vertx.createHttpServer();
    }
}

java.lang.NullPointerException
在 com.webinterface.vertxFacadeTest.createServer(vertxFacadeTest.java:23) 处发生
//第23行是这里:HttpServer httpServer = vertx.createHttpServer();

是否有人有想法为什么会这样?
期待解答 vertx.createHttpServer() 抛出 NullPointerException

英文:

I am playing a bit around with vertx.

Why does this code throws a NullPointerException?

import io.vertx.core.http.HttpServer;
import io.vertx.core.AbstractVerticle;

class vertxFacadeTest extends AbstractVerticle
{

    @Test
    void createServer()
    {
        HttpServer httpServer = vertx.createHttpServer();
    }
}


java.lang.NullPointerException
at com.webinterface.vertxFacadeTest.createServer(vertxFacadeTest.java:23) //line 23 is this here: HttpServer httpServer = vertx.createHttpServer();

Has anybody an idea why?
Looking forward vertx.createHttpServer() 抛出 NullPointerException

答案1

得分: 3

你的 Vertx 实例为空。当前你的类继承自 AbstractVerticle,这意味着它有一个 vertx 实例变量,但该变量并未在构造函数中初始化;它只会在 AbstractVerticle.init() 方法中被设置为实际值,而这个方法只会在部署 Verticle 时由 Vert.x 调用。所以在你的情况下,当 JUnit 实例化这个类时,vertx 为 null。

你不应该让测试类继承 AbstractVerticle。相反,应该在测试类中显式创建 Vertx 实例,可能会使用一个带有 @Before 注解的方法。关于 Vert.x 与 JUnit 集成的文档可以在这里找到。

英文:

Your Vertx instance is null. Right now your class extends AbstractVerticle, which means that it has a vertx instance variable, but that is not initialized in its constructor; it's only set to a real value in the AbstractVerticle.init() method, which is only called by Vert.x when you deploy the Verticle. So in your case, when JUnit instantiates the class, vertx is null.

You shouldn't have the test class extend AbstractVerticle. Instead, create the Vertx instance explicitly in the test class, probably using a method annotated with @Before. See the documentation on Vert'x integration with JUnit here.

huangapple
  • 本文由 发表于 2020年9月9日 02:21:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63799591.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定