JUnit 5 与以前版本的 JUnit 不同,拆分成由三个不同子项目的几个不同模块组成。
JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage
该API的基本特性 - 注解、断言等在平时的单元测试是常用的。与JUnit4相比,部分注解的名称有改变。
示例代码如下:
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)."); } }
执行结果:
主要注解解释:
断言 (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