关于springboot:Junit4升级至Junit5

为什么要降级

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}")

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理