Junit4升级至Junit5

699 阅读1分钟

为什么要升级

junit5的特性和优点可以参考升级到junit5。其中我最看中的点是,Junit4错过了好多Java8的好多特性。Junit5可以很好得利用java8的特性,代码的表达更加清晰和简洁。

以下升级方式即能兼容原来junit4的单测(不需要改存量单测),又能使用junit5的新特性,是不是很爽!

升级的具体步骤

pom中引入依赖

<dependencyManagement>
    <dependencies>
		<!-- 引入junit5的bom -->        
		<dependency>
            <groupId>org.junit</groupId>
            <artifactId>junit-bom</artifactId>
            <version>5.5.2</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
	<!-- Jupiter -->
	<dependency>
    	<groupId>org.junit.jupiter</groupId>
    	<artifactId>junit-jupiter</artifactId>
    	<scope>test</scope>
	</dependency>


	<!-- 用于兼容Junit4和junit3 -->
	<dependency>
    	<groupId>org.junit.vintage</groupId>
    	<artifactId>junit-vintage-engine</artifactId>
    	<scope>test</scope>
	</dependency>
</dependencies>

另外要注意 maven-surefire-plugin 的版本,junit5 要求插件版本必须要高于等于 2.22.0

<!-- JUnit 5 requires Surefire version 2.22.0 or higher -->
<build>
    <plugins>
	<plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.0</version>
	</plugin>
    </plugins>
</build>

新建junit5单测应用入口

@ExtendWith(SpringExtension.class)
@SpringBootTest
@ActiveProfiles("ut")
@Transactional
public class ApplicationJunit5Test {
}

新增的 junit5 单测继承 MochaApplicationJunit5Test 即可

异常重试功能

在单测执行中,遇到数据库死锁的异常,最直观的想法是进行重试,junit5支持异常重试,具体操作如下

引入rerunner-jupiter

<dependencies>    
	<dependency>
        <groupId>io.github.artsok</groupId>
        <artifactId>rerunner-jupiter</artifactId>
        <version>2.1.6</version>
        <scope>test</scope>
    </dependency>
</dependencies>

针对具体单测添加重试注解

各一个用户中心重试的例子,针对 MySQLTransactionRollbackException 异常进行了3次重试。更多技能解锁,请移步rerunner-jupiter文档

注意,方法上不要再重复添加 @Test 注解

@RepeatedIfExceptionsTest(repeats = 3,
        exceptions = MySQLTransactionRollbackException.class,
        name = "Retry deadlock failed test. Attempt {currentRepetition} of {totalRepetitions}")