关于springboot:Junit4升级至Junit5

1次阅读

共计 1227 个字符,预计需要花费 4 分钟才能阅读完成。

为什么要降级

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>

异样重试性能

在单测执行中,遇到数据库死锁的异样,最直观的想法是进行重试,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 文档

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