1、单元测试种类

1、Android项目的单元测试种类

  • 单元测试分为两种:
  • Java测试(module-name/src/test/java/)

在Java虚拟机(JVM)上本地运行的单元测试。当您的测试没有Android框架依赖关系或者您可以模拟Android框架依赖关系时,使用这些测试来最小化执行时间。

  • Android测试(module-name/src/androidTest/java/)

在Android设备或模拟器上运行的单元测试。这些测试可以访问Instrumentation信息,例如您正在测试的应用程序的上下文。当您的测试具有模拟对象无法满足的Android依赖关系时,请使用 这些测试。

  • 新建一个Android项目,就可以看到上述的两种单元测试

image.png

  • 引用的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);
    }
}
  • 运行结果:通过

image.png

  • 修改下代码,让单元测试不符合预期报错,效果如下

image.png

导出单元测试结果

  • 导出单元测试结果,这里选择HTML格式

image.png
image.png

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手机或者模拟器上运行

image.png

  • 导出报告

image.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码充电宝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值