AndroidJUnit4和参数化测试 [英] AndroidJUnit4 and Parameterized tests

查看:140
本文介绍了AndroidJUnit4和参数化测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Google provide new classes to write tests for Android, and especially using jUnit 4: https://developer.android.com/tools/testing-support-library/index.html

我想知道是否可以从jUnit使用AndroidJUnit4运行程序以及参数化的运行程序?

I was wondering if it is possible to use the AndroidJUnit4 runner, as well as the Parameterized one, from jUnit?

推荐答案

当前接受的答案未提供解释,链接的示例也无法很好地说明需要完成的工作.这是一个更完整的解释,希望可以节省一些人,避免我花时间去弄清楚这个问题.

The current accepted answer doesn't provide an explanation, and the linked example isn't great at showing what needs to be done. Here's a more complete explanation that will hopefully save someone from spending the time I did figuring this out.

尽管文档并没有使这个超级明显,但实际上它很容易设置!只要您在模块build.gradle文件中设置了testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner",就可以在已测试的Android测试中使用其他运行程序.如果已设置,则无需在已测试的测试中显式设置@RunWith(AndroidJUnit4.class).

While the documentation doesn't make this super obvious, it's actually surprisingly easy to set up! You are able to use another runner with instrumented Android tests as long as you set testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" in your module build.gradle file. If that is set, you do not need to explicitly set @RunWith(AndroidJUnit4.class)in your instrumented tests.

一个最小的示例如下:

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

If you also have the need to run some tests individually and others parameterized in the same test class, see this answer on using the Enclosed runner: https://stackoverflow.com/a/35057629/1428743

这篇关于AndroidJUnit4和参数化测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆