AndroidJUnit4 and Parameterized tests
Asked Answered
P

1

26

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

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

Plano answered 9/4, 2015 at 12:3 Comment(0)
T
23

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.

A minimal example would look like this:

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);
    }
}

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://mcmap.net/q/329380/-when-using-junit-39-s-parameterized-can-i-have-some-tests-still-run-only-once-duplicate

Toothy answered 3/10, 2017 at 21:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.