Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use multiple custom test runners in Android?

I am overriding Dagger 2 Components to mock dependencies in Android. For this I am using custom JUnit TestRunners.

It seems in my app/build.gradle I can set only one testRunner.

defaultConfig {
    applicationId 'com.xxx.xxx'
    minSdkVersion 18
    targetSdkVersion 23
    versionCode 1
    versionName '1.0.0'

    testInstrumentationRunner 'com.xxx.xxx.DgMockTestRunner'
}

How can I set multiple test runners? I would like every test class I write to have a separate TestRunner?

like image 854
eurosecom Avatar asked Oct 17 '25 06:10

eurosecom


1 Answers

You can use the @RunWith annotation in your test classes to specify the test runner class:

@RunWith(FooTestRunner.class)
public class TestFoo {
    @Before
    public void setUp();
}

However, in general you can probably accomplish what you want to do using JUnit rules. For example, the following DaggerMock rule instantiates a new MyComponent with a MyModule and sets this as the root component in the application:

@Rule public DaggerMockRule<MyComponent> daggerRule = new DaggerMockRule<>(MyComponent.class, new MyModule())
        .set(new DaggerMockRule.ComponentSetter<MyComponent>() {
            @Override public void setComponent(MyComponent component) {
                App app = (App) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext();
                app.setComponent(component);
            }
        });
like image 77
David Rawson Avatar answered Oct 19 '25 23:10

David Rawson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!