假设(Assumptions)
重要性:★★★☆☆
从JUnit 4开始在测试中支持假设Assumptions
。JUnit Jupiter的假设都是org.junit.jupiter.api.Assumptions
类的静态方法。
当假设assumption
失败时,余下的测试内容会终止执行,测试被标识为aborted
状态(而不是失败failed
),直接终止。与断言失败不同,当断言assertion
失败时,测试会被认定为失败failed
状态。
假设的典型应用场景是:当一个测试方法继续执行没有意义的时候——例如,测试所依赖的环境条件不满足时——终止测试的继续执行。
下面是代码示例:
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.junit.jupiter.api.Assumptions.assumingThat;
import example.util.Calculator;
import org.junit.jupiter.api.Test;
class AssumptionsDemo {
private final Calculator calculator = new Calculator();
@Test
void testOnlyOnCiServer() {
assumeTrue("CI".equals(System.getenv("ENV")));
// remainder of test
}
@Test
void testOnlyOnDeveloperWorkstation() {
assumeTrue("DEV".equals(System.getenv("ENV")),
() -> "Aborting test: not on developer workstation");
// remainder of test
}
@Test
void testInAllEnvironments() {
assumingThat("CI".equals(System.getenv("ENV")),
() -> {
// perform these assertions only on the CI server
assertEquals(2, calculator.divide(4, 2));
});
// perform these assertions in all environments
assertEquals(42, calculator.multiply(6, 7));
}
}