java.lang.NullPointerException 在 io.dropwizard.testing。junit5.DropwizardExtensionsSupport.beforeEach

java.lang.NullPointerException at io.dropwizard.testing.junit5.DropwizardExtensionsSupport.beforeEach

我正在尝试测试 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(TestMethodTestDescriptor.java:159)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeMethodsOrCallbacksUntilExceptionOccurs(TestMethodTestDescriptor.java:195)
    ...

坦率地说,这没有提供任何信息。有人可以指出这里有什么问题吗?

P/S 这里是 CommonObjects 构造函数:

    public CommonObjects(MyAppConfig configuration, EmailClient emailClient) {
        ApplicationConfig appConfig = configuration.getAppConfig();
        this.years = appConfig.getYears();
        this.emailClient = emailClient;
    }

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

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

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

然后,我在测试 class 中初始化 ResourceExtension 时使用了这些存根:

private static final EmailClient emailClient = mock(EmailClient.class);
private static final ResourceExtension EXT = ResourceExtension.builder()
            .addResource(new CommonObjects(new MyAppConfigStub(), emailClient))
            .build();

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