为你的Android添加第一个单元测试
续上篇《从Kotlin双锁单例中学习到…》,我们为这个加解密单例添加一个单元测试,继续优化我们的代码。从这篇你可以了解到:
-
Android单元测试的添加
-
单元测试的生命周期
-
单元测试的Mock对象
-
断言的使用
Andorid单元测试的添加
testImplementation 'junit:junit:4.13.1'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
步骤1,这里是使用junit来进行andorid的单元测试,因此在模块的build.gradle下dependencies加入junit依赖包
步骤2方式一:在对应模块-src-test-java下,添加一个kotlin或java的类SecurityHelperTest,我这里是kotlin的语言
步骤2方式二:在需要被测试的类的代码中,右键-Go To-Test,创建单测类SecurityHelperTest
单元测试的生命周期
class SecurityHelperTest{
@Before
fun init(){
println("===@Beforeinitcalled===")
}
@After
fun clearDataForTest(){
println("===@AfterclearDataForTestcalled==="