Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between AndroidJUnitRunner and AndroidJunit4?

Tags:

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:

enter image description here

And, AndroidJunit4 extends from,

enter image description here

So, what is the difference between the two runners and which runner am I supposed to be using finally?

like image 712
Manish Kumar Sharma Avatar asked Aug 27 '17 15:08

Manish Kumar Sharma


People also ask

What is AndroidJUnit4?

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 { ... }

Why do you use the AndroidJUnitRunner when running UL tests?

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.


1 Answers

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!

like image 62
dominicoder Avatar answered Oct 21 '22 15:10

dominicoder