配置:
1.Tool-->Android-->SDK Manager -->SDK Tools-->Support Repositoty. install 即可
2.app-->build gradle 配置:
android { compileSdkVersion 24 buildToolsVersion "24.0.3" defaultConfig { applicationId "com.example.administrator.myapplication" minSdkVersion 15 targetSdkVersion 24 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" //junit4 相关配置 } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:24.2.1' compile 'com.android.support:design:24.2.1' testCompile 'junit:junit:4.12' //junit4相关配置 }
Junit4的使用:
1.新建一个类用于测试:
public class add { public int runadd(int a,int b){ return a+b; } }2.新建测试类:@before @after 测试方法前后执行 @test 被执行的方法 @category类别器
import android.util.Log; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.*; public class TestJunit { @Before public void testA(){ Log.d("LC","before"); } @Category(Categotysuite1.class) //category 类别器的名称 @Test public void testB(){ add A = new add(); int r = A.runadd(2,2); assertNotEquals(r,3); } @Test public void testC(){ add A = new add(); int r = A.runadd(1,2); assertEquals(r,3); } @After public void testD(){ Log.d("LC","after"); } }
3.runner类(打包测试类):
import org.junit.experimental.categories.Categories; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Categories.class) //指明以类别器运行,也可以指定为套件运行(Suite.class) @Categories.IncludeCategory(CategorySuite1.class) // @Suite.SuiteClasses(TestJunit.class) public class AllTestCases { }
@RunWith(Categories.class)当指定以类别器运行时,只会运行有@Category的测试方法,同时会结合Categories.IncludeCategory(运行指定方法)和ExcludeCategory(去除此标签内的测试方法)进行过滤。
但是当@RunWith(Suite.class)指定以Suite运行是,Categories.IncludeCategory()和ExcludeCategory()会失效,会运行所有带@test标签的测试方法
可以用以下代码分别进行验证:
@RunWith(Suite.class) @Categories.ExcludeCategory(CategorySuite1.class) @Suite.SuiteClasses(TestJunit.class) public class AllTestCases { }
@RunWith(Categories.class) @Categories.ExcludeCategory(CategorySuite1.class) @Suite.SuiteClasses(TestJunit.class) public class AllTestCases { }
junit4 执行单个测试类执行,例如,可将光标定位到测试类TestJunit名称处,右击鼠标选择run,即可单独执行TestJunit类,而不需要每次都执行,方便调试
可能遇到的问题:
运行case的时候,如果没有执行case,提示:Test running failed: Unable to find instrumentation info for: ComponentInfo{com.umeng.message.example.test/android.test.InstrumentationTestRunner} Empty test suite.
可能的原因
1.在build.gradle 中,defaultConfig下,没有配置如下语句
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
2、在Run/Debug Configuration中,Specific instrumentation runner(optial) 中,添加的配置与第一步中的配置名称不一致
android.support.test.runner.AndroidJUnitRunner