1. 测试目录
Android Studio 中的典型项目包含两个用于放置测试的目录。
androidTest 目录应包含在真实或虚拟设备上运行的测试。此类测试包括集成测试、端到端测试,以及仅靠 JVM 无法完成应用功能验证的其他测试。
test 目录应包含在本地计算机上运行的测试,如单元测试。
2. 测试金字塔的级别
小型测试(Unit tests)占 70%,中型测试(Integration tests)占 20%,大型测试(UI tests)占 10%
3. 创建本地单元测试类
JUnit 是最受欢迎且应用最广泛的 Java 单元测试框架
一般情况app/build.gradle自动添加
dependencies {
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
测试目录下已经生成如下文件, 我们可以根据需要创建test case
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
4. instrumented tests
也已经自动生成了文件
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.android.unitinstrumenttest", appContext.getPackageName());
}
}
可以根据插件 "Test Recorder" 根据你的操作,自动生成测试用例
前提需要在Android Studio 添加这个插件: File → Settings → Plugin -> Test Recorder
添加后, Run - > Record Espresso Test 即可
参考:
https://developer.android.com/training/testing
https://stackoverflow.com/questions/16586409/how-can-i-create-tests-in-android-studio