你好啊,我是大阳。
这是专栏《SpringBoot自动化单元测试教程》的第四篇文章。本文我们将讨论JUnit5的假设、测试套件和条件测试。
1. JUnit5 假设
JUnit 5假设类提供静态方法来支持基于假设的条件测试执行。假设失败会导致测试中止。
当继续执行给定的测试方法没有意义时,通常使用假设。在测试报告中,这些测试将被标记为通过。
JUnit Assumptions(假设)类有以下方法:
- Assumptions.assumeTrue()
- Assumptions.assumeFalse()
- Assumptions.assumingThat()
1.1 Assumptions.assumeTrue()
该方法验证给定假设为真,如果假设为真,则测试继续进行,否则,测试执行将中止。
它具有以下重载方法:
public static void assumeTrue(boolean assumption) throws TestAbortedException
public static void assumeTrue(boolean assumption, Supplier<String> messageSupplier) throws TestAbortedException
public static void assumeTrue(boolean assumption, String message) throws TestAbortedException
public static void assumeTrue(BooleanSupplier assumptionSupplier) throws TestAbortedException
public static void assumeTrue(BooleanSupplier assumptionSupplier, String message) throws TestAbortedException
public static void assumeTrue(BooleanSupplier assumptionSupplier, Supplier<String> messageSupplier) throws TestAbortedException
示例:
package cn.dayangshuo.junit5.tests;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
/**
* @author DAYANG
*/
public class AssumeTests {
@Test
void testOnDev() {
System.setProperty("ENV", "DEV");
Assumptions.assumeTrue("DEV".equals(System.getProperty("ENV")));
System.out.println("测试继续执行...");
}
/**
* 测试失败,打印出失败消息
*/
@Test
void testOnProd() {
System.setProperty("ENV", "PROD");
Assumptions.assumeTrue("DEV".equals(System.getProperty("ENV")), AssumeTests::message);
System.out.println("测试不会继续执行,不会打印此行...");
}
private static String message