单元测试JUnit5上手

时间:2020-08-17 08:25:35   收藏:0   阅读:239

1. JUnit5的架构

JUnit 5 与以前版本的 JUnit 不同,拆分成由三个不同子项目的几个不同模块组成。

JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage

技术分享图片

2. JUnit Jupiter API 的使用

该API的基本特性 - 注解、断言等在平时的单元测试是常用的。与JUnit4相比,部分注解的名称有改变。

2.1 JUnit Jupiter注解

技术分享图片

 示例代码如下:

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import static org.junit.jupiter.api.Assertions.assertEquals;

@Slf4j
@SpringBootTest
class Junit5demoApplicationTests {

    @Test
    void contextLoads() {
        log.info("default contextLoads running");
    }

    @BeforeAll
    public static void init() {
        log.info("Before All, only run once on the start ");
    }

    @AfterAll
    public static void done() {
        log.info("After All, only run once on the end ");
    }

    @BeforeEach
    public void setUp() throws Exception {
        log.info("Before Each, run once on the every start ");
    }

    @AfterEach
    public void tearDown() throws Exception {
        log.info("After Each, run once on the every end ");
    }

    @Test
    @DisplayName("Dummy test")
    void aTest() {
        log.info("As written, this test will always pass!");
        assertEquals(4, (2 + 2));
    }

    @Test
    @Disabled
    @DisplayName("A disabled test")
    void testNotRun() {
        log.info("This test will not run (it is disabled, silly).");
    }
}

执行结果:

技术分享图片

 主要注解解释:

2.2 JUnit Jupiter断言

断言 (assertion) 是 org.junit.jupiter.api.Assertions 类上的众多静态方法之一。断言用于测试一个条件,该条件必须计算为 true ,测试才能继续执行。
如果断言失败,测试会在断言所在的代码行上停止,并生成断言失败报告。如果断言成功,测试会继续执行下一行代码。

技术分享图片

使用如下:

技术分享图片

如果不正确,会打印如下信息:

技术分享图片

通过上面发现一个问题,一些断言顺序执行,如果中途出现一个断言失败,那么接下去的断言就会中止,所以引入另一个断言 assetAll() 来保证所有断言能够顺利执行。使用如下:

技术分享图片

 Junit5中新添加了对方法抛出异常的断言Assertions类中的assertThrows()和assertDoesNotThrow(),使用此方法可以对被测试方法抛出的异常进行断言测试,使用如下:

技术分享图片

 

 

 

 

 

 

参考:

https://v.youku.com/v_show/id_XMjk1NTY4MTkxNg==.html

 

原文:https://www.cnblogs.com/zjfjava/p/13515283.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!