Disco S2 Disco S2 - 5 months ago 13
Android Question

Using Different Test Runners For Different Tests

I am using

Dagger 2
and trying to provide different dependencies at test time.

I can provide different dependencies for the tests but unfortunately, these then apply to all tests in the
androidTest
directory.

I do this by specifying a
TestAppComponent
which uses a
TestAppModule
. In my
TestApplication
, which extends my
AndroidApplication
, I supply the
TestAppComponent
rather than the real
AppComponent
. Then I have
TestRunner
that extends the
newApplication
method like so:

@Override
public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return super.newApplication(cl, TestApplication.class.getName(), context);
}


Then to use this runner I replace the current runner with the following:

testInstrumentationRunner "com.company.myapp.TestRunner"


My Question

How do I use a different component/application/test runner for different tests rather than use the same for each one? I may want to mock a dependency in one test but not in another?

Answer

I have found a solution to this in a blog post. It bypasses creating a custom runner and instead uses a Rule to set a different component within the loaded Application. This means you can supply different components for each test class which is what I wanted to do.

The blog post by the guys at Ribot Labs can be found here

Comments