2.5、Assumptions
JUnit Jupiter
包含一部分JUnit4
得假设方法,还新增加了能与Java8
得lambda
表达式和方法引用结合很好得假设方法。所有得JUnit Jupiter
假设方法都在org.junit.jupiter.api.Assumptions
类得静态方法。
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));
}
}
在
JUnit Jupiter 5.4
版本中,是允许使用JUnit4
得org.junit.Assume
类来假设。具体说,JUnit Jupiter
支持JUnit4
得AssumptionViolatedException
来表示一个方法应该被终止而不是标记为失败。