首页 > 解决方案 > NullPointerException 使用 DropwizardAppExtension 和 JUnit5

问题描述

我的 DropWizard JAX-RS 项目正在使用 DW 现已弃用的 JUnit 4 规则进行测试,这至少有效。我最近尝试更改为 JUnit 5 并使用主流方法进行测试,但我什至无法启动测试。DW 在加载我的测试时给出了一个类加载异常,但深深地埋在了原因中——有一行“Caused by: java.lang.NullPointerException: environment”。为简洁起见,我删除了大部分其他行:

 java.lang.Exception: java.lang.ExceptionInInitializerError
    at io.dropwizard.testing.junit5.DropwizardExtensionsSupport.beforeAll(DropwizardExtensionsSupport.java:87)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeBeforeAllCallbacks$8(ClassBasedTestDescriptor.java:368)
...
    Suppressed: java.lang.Exception: java.lang.NoClassDefFoundError: Could not initialize class com.idfconnect.myapp.ws.test.MyAppServiceTest
...
    Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.idfconnect.myapp.ws.test.MyAppServiceTest
...
Caused by: java.lang.NullPointerException: environment
    at java.util.Objects.requireNonNull(Objects.java:228)
    at io.dropwizard.testing.DropwizardTestSupport.getEnvironment(DropwizardTestSupport.java:371)
    at io.dropwizard.testing.DropwizardTestSupport.getObjectMapper(DropwizardTestSupport.java:375)
    at io.dropwizard.testing.junit5.DropwizardAppExtension.getObjectMapper(DropwizardAppExtension.java:242)
    at io.dropwizard.testing.junit5.DropwizardAppExtension.clientBuilder(DropwizardAppExtension.java:279)
    at io.dropwizard.testing.junit5.DropwizardAppExtension.client(DropwizardAppExtension.java:271)
    at com.idfconnect.myapp.ws.test.MyAppServiceTest.<clinit>(MyAppServiceTest.java:38)
    ... 46 more

我有点不知道为什么它失败了。显然,它正在加载类并尝试对其进行初始化,并且 DropwizardTestSupport 中对 getEnvironment 的调用返回 null。

这是测试类的顶部:

@ExtendWith(DropwizardExtensionsSupport.class)
public class MyAppServiceTest {
    static Logger                                                 logger = LoggerFactory.getLogger(MyAppServiceTest.class);
    static final String                                           BASE_URI     = "http://localhost:8080/myapp";
    private static DropwizardAppExtension<MyAppConfiguration> mkApp        = new DropwizardAppExtension<>(
            MyAppApplication.class,
            ResourceHelpers.resourceFilePath("my-app-config.yaml"));
    private static Client                                         client = mkApp.client();

任何建议表示赞赏!

我要注意的唯一另一件事是应用程序本身运行良好

标签: jax-rsjunit5dropwizard

解决方案


万一其他人遇到同样的问题,这完全是由于将“客户端”设置为静态引起的。

 private static Client client = mkApp.client();

一旦我将客户端设置为实例变量,它就可以正常工作。去搞清楚...


推荐阅读