jax-rs - 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();
任何建议表示赞赏!
我要注意的唯一另一件事是应用程序本身运行良好
解决方案
万一其他人遇到同样的问题,这完全是由于将“客户端”设置为静态引起的。
private static Client client = mkApp.client();
一旦我将客户端设置为实例变量,它就可以正常工作。去搞清楚...
推荐阅读
- javascript - 禁用字段集无法按预期工作
- docker - 无法在本地 Kubernetes 集群上公开端口(通过 Docker Desktop)
- python - pandas:使用 groupby wrt date 添加/追加行
- .net - Docker .NET Core 连接到 VPN Postgres
- oracle - 如何使用变量来更改 PL SQL 中表的约束?
- python - 如何将列表中的第一项设置为字典键,并将以下项设置为该键的值?
- java - Hybris 错误 - 没有租户活动。如果您不想使用租户,请调用 Registry.activateMasterTenant() 以确保主租户处于活动状态
- php - 在 Laravel 中没有从 FollowButton.vue 文件中得到响应
- linux - 在 Linux 中比较文本文件中两列的特定部分
- c++ - 我需要帮助返回列表前面的元素*无需*使用迭代器类(假设列表不为空)