Currently Google is recommended to use Androidjunitrunner for unit testing.
If you want to use Instrumentationtestrunner for unit testing, the following article is recommended:
http://blog.csdn.net/zhaokaiqiang1992/article/details/45332513
When testing with Androidjunitrunner, you need to add the following code to the Build.gradle:
Defaultconfig { //... Testinstrumentationrunner "Android.support.test.runner.AndroidJUnitRunner" }
dependencies { //... Androidtestcompile ' com.android.support.test:runner:0.3 '}
This sentence testinstrumentationrunner indicates that to use Androidjunitrunner for unit testing, if this sentence is not written it is likely to cause the following error:
Junit.framework.AssertionFailedError:No tests found in Andriodjunit.robot.com.andriodjunitrunner.CalcTest
and Androidtestcompile ' com.android.support.test:runner:0.3 ' indicates a reference to the relevant library, and when this word is not added, our external Libraries
After joining,
From here we can see that after adding runner:0.3, the Juint library will be added automatically without us having to add the Juint library again.
After the basic work is done, we start the code for our unit tests.
Add files to the package that corresponds to SRC/MAIN/JAVA/XXX:
public class Calc {public int sum (int a, int b) { return a + b; } public int sub (int a, int b) {return a-a ; }}
Select this class, right-click,
Next:
Generate the following code:
public class Calctest { @Test public void Testsum () throws Exception { } @Test public void TestSub () Throws Exception { }}
Then it is simple to use JUNIT4 for unit testing, first add the test code:
public class Calctest { @Test public void Testsum () throws Exception { Calc calc = new Calc (); Assertequals (6, Calc.sum (2, 4)); } @Test public void TestSub () throws Exception { Calc calc = new Calc (); Assertequals (9, Calc.sub (2, 4));} }
Select the Calctest class and right-click:
Run results
This is done using Androidjunitrunner for simple unit testing, and if you need to unit test the interface (Activity), you need to introduce espresso.
Here is no longer explained, please refer to the previous article.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Studio uses Androidjunitrunner for unit testing