Junit4&Junit5对比

Junit是Java编程语言的单元测试框架,用来编写单元测试代码。随着Junit5的盛行,与Junit4有何差异。


JDK支持
Junit4需要Java5+版本

Junit5需要Java8+版本

Maven依赖
Junit4不区分模块,只有一个jar:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>
Junit5分为3个模块:

junit-jupiter: junit5核心模块,提供了junit5的新编程模型。包含了一个测试引擎,用于junit-platform上运行。

junit-platform:平台功能模块,其他测试引擎可以基于此平台接入junit。

junit-vintage:用于兼容junit3,junit4的测试引擎。

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>RELEASE</version>
    <scope>test</scope>
</dependency>
springboot版本依赖
spring-boot 2.2版本之前默认使用Junit4;2.2之后的版本使用的则是Junit5。

注解区别

Junit4中的@Test是import org.junit.Test;

Junit5中的@Test是import org.junit.jupiter.api.Test;


断言方法

Junit4中断言内容位于org.junit.Assert类;

Junit5中断言内容位于org.junit.jupiter.api.Assertions类;

// junit4
org.junit.Assert.assertEquals(1.0, 1.0);
 
// junit5
org.junit.jupiter.api.Assertions.assertEquals(1.0, 1.0);


测试手法
重复测试:

/**
 * junit4需要手动new repeatTest
 */
@Test
public void repeatTest4(){
    TestSuite suite = new TestSuite();
    // 10表示重复测试次数
    suite.addTest(new RepeatedTest(new TestSample(), 10));
}
 
/**
 * junit5通过使用@RepeatedTest注解方法并指定所需的重复次数
 */
@org.junit.jupiter.api.RepeatedTest(10)
public void repeatTest5(){
    // todo...
}
写法差异
Junit5:

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
 
public class DemoTest {
    @Test
    void test() {
        assertEquals(2, 1);
    }
}
Junit4:

package tech.pdai.junit4;
 
import org.junit.Test;
import static org.junit.Assert.assertEquals;
 
public class HelloWorldTest {
    @Test
    public void DemoTest() {
        assertEquals(2, 1);
    }
可以看到Junit5写法上除了导入的包不一致外,还支持非public的方法测试。

小结
以上是对常见的一些用法差异的总结。Junit5在Junit4的基础上,增加了一些新的特性。增加了基于lambda的支持,同时简化了一些测试手法的编写,如重复性测试,参数化测试等等。Junit5配合mockito等测试框架,使用体验上还是不错的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值