首页 > 解决方案 > 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;
    }

这也解释了为什么我在每个测试用例之前创建资源扩展。

标签: javajunitnullpointerexceptionjunit5dropwizard

解决方案


最后,我没有使用模拟,而是创建了从具体类扩展的存根。

例如,对于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();

这将允许在声明时初始化资源扩展,即使我们在初始化期间调用其他依赖项中的方法。


推荐阅读