1、Android项目的单元测试种类
- 单元测试分为两种:
- Java测试(module-name/src/test/java/)
在Java虚拟机(JVM)上本地运行的单元测试。当您的测试没有Android框架依赖关系或者您可以模拟Android框架依赖关系时,使用这些测试来最小化执行时间。
- Android测试(module-name/src/androidTest/java/)
在Android设备或模拟器上运行的单元测试。这些测试可以访问Instrumentation信息,例如您正在测试的应用程序的上下文。当您的测试具有模拟对象无法满足的Android依赖关系时,请使用 这些测试。
- 新建一个Android项目,就可以看到上述的两种单元测试
- 引用的dependencies也会区分这两种
- testImplementation:Java测试
- androidTestImplementation:Android测试
dependencies {
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
2、Java测试
- 先看下JVM环境下的ExampleUnitTest,@Test表示该方法是需要测试的
package com.arthur.unittest;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
// 断言是否相等,如果相关表示该条单元测试通过
// 第一个参数,预期结果是4,第二个参数是运行的结果
assertEquals(4, 2 + 2);
}
}
- 运行结果:通过
- 修改下代码,让单元测试不符合预期报错,效果如下
导出单元测试结果
- 导出单元测试结果,这里选择HTML格式
3、Android测试
- 看下androidTest下面的ExampleInstrumentedTest
package com.arthur.unittest;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.arthur.unittest", appContext.getPackageName());
}
}
- 运行结果如下,这种方式的测试需要在Android手机或者模拟器上运行
- 导出报告