使用Junit5将上下文导入测试类

owfi6suc  于 2022-11-11  发布在  其他
关注(0)|答案(2)|浏览(173)

我们使用Junit 5框架在您的Android项目中进行单元测试。如何将上下文导入这些测试类?
使用的插件; https://github.com/mannodermaus/android-junit5

kqqjbcuj

kqqjbcuj1#

现在我找到了这个解决方案。方法参数化调用了额外的代码,但解决了我的问题。
您的测试类应该具有扩展名@ExtendWith(MyExtension.class)例如,

@ExtendWith(MyExtension.class)
public class MyTestScript {
    // tests
}

扩展类应实现ParameterResolver接口,如下图:

public class MyExtension implements ParameterResolver {
    @Override
    public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
            throws ParameterResolutionException {
        return true; // if you supports parameters in the test class
    }

    @Override
    public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
            throws ParameterResolutionException {
        return extensionContext; // includes context which can be used in the test script
    }

所以,在测试脚本中,你应该参数化所有你想使用context的方法:

@ExtendWith(MyExtension.class)
public class MyTestScript {
    @BeforeAll
    void beforeAll(ExtensionContext context) {
        logger.logInfo(context, "BeforeAll execution");    }

    @AfterAll
    void afterAll(ExtensionContext context) {
        logger.logInfo(context, "AfterAll execution");
    }

    @BeforeEach
    void beforeEach(ExtensionContext context) {
        logger.logInfo(context, "BeforeEach execution");
    }

    @AfterEach
    void afterEach(ExtensionContext context) throws InterruptedException {
        logger.logInfo(context, "AfterEach execution");
    }

    @Test
    void exampleTest(ExtensionContext context) {
        logger.logInfo(context, "Test execution");
    }
}
aoyhnmkz

aoyhnmkz2#

可以使用Roboelectric获取上下文
第一个

相关问题