I am a newbie to the Android testing world and the samples for Unit tests mention the use of AndroidJunit4
runner. I have stumbled upon another runner called AndroidJUnitRunner
. Now, I saw the docs for both the classes and at one glance, it seems that the difference is that AndroidJunit4
supports JUnit4 especially while AndroidJUnitRunner
supports JUnit3 and JUnit4 but if you look into the class structure and the available methods, there actually is a huge difference between these two runners.
For ex, AndroidJUnitRunner
extends from the following classes:
And, AndroidJunit4
extends from,
So, what is the difference between the two runners and which runner am I supposed to be using finally?
AndroidJUnit4 is the class test runner. This is the thing that will drive the tests for a single class. You annotate your test classes with this: @RunWith(AndroidJUnit4. class) public class MyActivityTest { ... }
When you use AndroidJUnitRunner to run your tests, you can access the context for the app under test by calling the static ApplicationProvider. getApplicationContext() method. If you've created a custom subclass of Application in your app, this method returns your custom subclass's context.
I recently have been spending quite a bit of time with these classes. Short answer: you use both.
AndroidJUnitRunner
is the instrumentation runner. This is essentially the entry point into running your entire suite of tests. It controls the test environment, the test apk, and launches all of the tests defined in your test package. You configure this in your gradle file:
android { defaultConfig { testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } }
AndroidJUnit4
is the class test runner. This is the thing that will drive the tests for a single class. You annotate your test classes with this:
@RunWith(AndroidJUnit4.class) public class MyActivityTest { ... }
The instrumentation runner will process each test class and inspect its annotations. It will determine which class runner is set with @RunWith
, initialize it, and use it to run the tests in that class. In Android's case, the AndroidJUnitRunner
explicitly checks if the AndroidJUnit4
class runner is set to allow passing configuration parameters to it.
An educational exercise is to put breakpoints in each of these classes and step through the code. This is what I did recently to learn the above information. Hope that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With