创建本地单元测试
●创建本地单元测试需要创建在:
module-name/src/test/java/
这个目录下,这个目录在使用Android Studio创建工程的时候,就会默认创建。
●还需要在build.gradle中添加dependencies,这一步在创建工程的时候也会自动依赖
testCompile 'junit:junit:4.12'
创建本地单元测试的两种方式:
●直接在上述目录下创建一个Test.java文件,然后写测试方法,比如:
public class Test { @org.junit.Test public void sum() throws Exception { Caculator caculator = new Caculator(); assertEquals(10, caculator.sum(1, 8), 0); } } |
该方法要加@Test的注解,才能标明这是测试方法,才能直接被运行。
Caculator 是被测试的类,可以是我们工程中的工具类什么鬼的
assertEquals()这个方法就是进行判断10 == sum(1, 8) ,结果是错误的。assert还有很多API
●在你的工具类基础上进行创建单元测试类:
比如Caculator类:
1.右键
2.GO TO
3.Test
4.Create New Test...
5.选中setUp/@Before
6.选择你要测试的方法
7.点击ok
8.选择目录为app\src\test\java\packagename
9.即可生成测试类
生成测试类之后,可以在setUp中对要测试的工具类进行初始化,如下:
Caculator mCaculator; @Before public void setUp() throws Exception { mCaculator = new Caculator(); } |
对需要测试的方法,写测试内容:
@Test public void sum() throws Exception { //测试sum方法 assertEquals(7d, mCaculator.sum(2d, 5d), 0); } |
运行测试:选择测试的方法运行,或者整个测试类运行,对类中的所有测试内容进行测试
使用Espresso,进行UI单元测试
在build.gradle中配置如下:
androidTestCompile 'com.android.support:support-annotations:25.0.0' androidTestCompile 'com.android.support.test:runner:0.5' androidTestCompile 'com.android.support.test:rules:0.5' androidTestCompile 'org.hamcrest:hamcrest-library:1.3' androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2' androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.2' //创建工程自动创建 androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) // defaultConfig { ... testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } |
●在面板是project的形势下,在src目录下找到androidTest,找到java,创建MainActivityInstrumentationTest 类 ,具体代码如下:
public class MainActivityInstrumentationTest { private static final String STRING_TO_BE_TYPED = "Peter"; @Rule public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>( MainActivity.class); @Test public void sayHello() { onView(withId(R.id.editText)).perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard()); //line 1 onView(withText("Say hello!")).perform(click()); //line 2 String expectedText = "Hello, " + STRING_TO_BE_TYPED + "!"; onView(withId(R.id.textView)).check(matches(withText(expectedText))); //line 3 } } |
●运行测试类即可返回测试结果
上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。