【单元测试】【Android】JUnit 4 和 JUnit 5 的差异记录

背景

Jetbrain IDE 支持生成 Test 类,其中选择JUnit5 和 JUnit,但是感觉这不是标准的单元测试,因为接口命名吧。

差异对比

两者生成的单测API名称同原API,没加test前缀的。使用差异主要表现在:

  • setUp & tearDown 的注解
  • 引用的junit包

| | JUnit 4 | JUnit 5 |
| setUp 注解 | Before | BeforeEach |
| tearDown 的注解 | After | AfterEach |
| 引用的junit包 | org.junit.Test | org.junit.jupiter.api.Test |
| 类名修饰符 | 有修饰符 public class UtilTest | 无修饰符, 默认 class UtilTest |

方法修饰符 有修饰符 @Before public void setUp() throws Exception { } 无修饰符, 默认@BeforeEach void setUp() { }
[JUnit 版本差异项]

代码template

JUnit 5

java 复制代码
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class UtilTest {

    @BeforeEach
    void setUp() {
    }

    @AfterEach
    void tearDown() {
    }

    @Test
    void customTypeSummary() {
    }

JUnit 4

要求类是公开public的,否则代码报错:

Test class 'UtilTest' is not constructable because it is not 'public'

java 复制代码
import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class UtilTest {

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void customTypeSummary() {
    }

另外有个疑问,怎么才能让main java 类文件能检测到对应的单元测试Coverage?是否跟类生成的方式或者Test类/API命名有关?

相关推荐
陈希瑞1 分钟前
【保姆级教程】安卓手机免Root一键部署AutoGLM:支持语音控制与自动化操作
android·智能手机·自动化
TheNextByte15 分钟前
如何将联系人从Android传输到计算机的 6 种方法
android
喂_balabala6 分钟前
excludeFromRecents
android
TimeFine30 分钟前
Android AI解放生产力(五)实战:解放写API接口的繁琐工作
android
csj503 小时前
安卓基础之《(6)—Activity组件(3)》
android
怀旧,3 小时前
【Linux系统编程】13. Ext系列⽂件系统
android·linux·缓存
Dabei3 小时前
Android 语音助手简单实现与语音助手“执行任务”交流
android·前端
jzlhll1233 小时前
android NDSDManager onResolveFailed errorCode=3的解决方案
android
芦半山4 小时前
四年之后,重新审视 MTE:从硬件架构到工程落地
android·安全
2501_916007474 小时前
iOS与Android符号还原服务统一重构实践总结
android·ios·小程序·重构·uni-app·iphone·webview