java - io.dropwizard.testing.junit5.DropwizardExtensionsSupport.beforeEach 处的 java.lang.NullPointerException
问题描述
我正在尝试测试 Dropwizard 资源。
我的测试如下所示:
@ExtendWith(DropwizardExtensionsSupport.class)
public class CommonObjectsTest {
private ResourceExtension EXT;
@BeforeEach
public void setup() {
ApplicationConfig applicationConfig = mock(ApplicationConfig.class);
when(applicationConfig.getYears()).thenReturn(1);
MyAppConfig myAppConfig = mock(MyAppConfig.class);
when(myAppConfig.getAppConfig()).thenReturn(applicationConfig);
EmailClient emailClient = mock(EmailClient.class);
CommonObjects commonObjects = new CommonObjects(myAppConfig, emailClient);
EXT = ResourceExtension.builder()
.addResource(commonObjects)
.build();
}
@Test
public void getYearsSuccessfully() {
Response response = EXT.target("/get_years").request().get();
System.out.println(response);
}
}
但是,这会给出错误消息:
java.lang.NullPointerException
at io.dropwizard.testing.junit5.DropwizardExtensionsSupport.beforeEach(DropwizardExtensionsSupport.java:123)
at io.dropwizard.testing.junit5.DropwizardExtensionsSupport.beforeEach(DropwizardExtensionsSupport.java:106)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeEachCallbacks$1(TestMethodTestDescriptor.java:159)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeMethodsOrCallbacksUntilExceptionOccurs$5(TestMethodTestDescriptor.java:195)
...
坦率地说,这是没有信息的。有人可以指出这里有什么问题吗?
P/S 这是CommonObjects
构造函数:
public CommonObjects(MyAppConfig configuration, EmailClient emailClient) {
ApplicationConfig appConfig = configuration.getAppConfig();
this.years = appConfig.getYears();
this.emailClient = emailClient;
}
这也解释了为什么我在每个测试用例之前创建资源扩展。
解决方案
最后,我没有使用模拟,而是创建了从具体类扩展的存根。
例如,对于ApplicationConfig
,我创建了ApplicationConfigStub
:
public class ApplicationConfigStub extends ApplicationConfig {
@Override
public int getYears() {
return 1;
}
}
而对于MyAppConfig
,我创建了MyAppConfigStub
:
public class MyAppConfigStub extends MyAppConfig {
@Override
public ApplicationConfig getAppConfig() {
return new ApplicationConfigStub();
}
}
ResourceExtension
然后,我在测试类中初始化时使用了这些存根:
private static final EmailClient emailClient = mock(EmailClient.class);
private static final ResourceExtension EXT = ResourceExtension.builder()
.addResource(new CommonObjects(new MyAppConfigStub(), emailClient))
.build();
这将允许在声明时初始化资源扩展,即使我们在初始化期间调用其他依赖项中的方法。
推荐阅读
- angular - FormGroup 不适用于带有 Angular 7 的 Ionic
- angular - 角度 svg 图像预览
- c++ - 如何在 C++ 应用程序中包含外部 PCH 文件?
- excel - 多层枢轴以不同方式处理层(SUM,MAX,SUM)
- sql - Postgresql 在特定时间间隔内创建的记录百分比
- containers - Podman 的权限问题
- docker - Docker compose:将随机容器端口传递给环境变量
- python - Python矩阵给出与最后一条记录相同的结果
- xamarin - xamarin表单列表视图中的粘性标题
- javascript - 反应 onClick 键码未定义?