AndroidJUnit4 和参数化测试

标签 android junit android-testing parameterized

Google 提供了新的类来为 Android 编写测试,尤其是使用 jUnit 4:https://developer.android.com/tools/testing-support-library/index.html

我想知道是否可以使用来自 jUnit 的 AndroidJUnit4 运行器以及参数化运行器?

最佳答案

当前接受的答案没有提供解释,并且链接的示例不能很好地说明需要做什么。这是一个更完整的解释,希望可以避免有人花时间我弄清楚这一点。


虽然文档并没有让这一点非常明显,但实际上设置起来非常容易!只要您在模块 build.gradle 文件中设置 testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" ,您就可以使用另一个运行器进行检测的 Android 测试。如果已设置,则无需在检测的测试中显式设置 @RunWith(AndroidJUnit4.class)

一个最小的例子如下所示:

build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 26

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
}

SampleParameterizedTest.java:

@RunWith(Parameterized.class)
public class SampleParameterizedTest {

    @Parameter(value = 0)
    public int mTestInteger;

    @Parameter(value = 1)
    public String mTestString;

    @Parameters
    public static Collection<Object[]> initParameters() {
        return Arrays.asList(new Object[][] { { 0, "0" }, { 1, "1" } });
    }

    @Test
    public void sample_parseValue() {
        assertEquals(Integer.parseInt(mTestString), mTestInteger);
    }
}

如果您还需要单独运行一些测试并在同一测试类中参数化其他测试,请参阅使用 Enclosed 运行器的答案:https://stackoverflow.com/a/35057629/1428743

关于AndroidJUnit4 和参数化测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29538008/

相关文章:

Android:将布局资源添加到库仅用于测试

android - Android uiautomator如何在EditText中填写密码?

android - 测试主屏幕小部件的最佳方法

Android:从 ListView/ArrayAdapter Activity 中删除项目

php - 使用 Retrofit 2 将 Pdf 上传到服务器

android - WebViews UID 与应用程序 UID 相同吗?

Android, BluetoothSocket - 我如何判断连接是否已经存在或者我是否必须调用连接?

java - Junit测试预期异常: java. io.FileNotFoundException,junit.framework.assertionFailedError

java - 用于将文件写入文件系统的代码的 JUnit 5 测试用例。 (文件.写入)

ant - 使用依赖于环境变量的代码进行单元测试