下面列出了怎么用org.junit.runners.model.Statement的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Implementation based on {@link TestWatcher}.
*/
@Override
public Statement apply(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
List<Throwable> errors = new ArrayList<Throwable>();
startingQuietly(description, errors);
try {
base.evaluate();
succeededQuietly(description, errors);
} catch (AssumptionViolatedException e) {
errors.add(e);
skippedQuietly(e, description, errors);
} catch (Throwable t) {
errors.add(t);
failedQuietly(t, description, errors);
} finally {
finishedQuietly(description, errors);
}
MultipleFailureException.assertEmpty(errors);
}
};
}
@Override
public Statement apply(Statement base, Description description) {
return this.temp.apply(new Statement() {
@Override
public void evaluate() throws Throwable {
before();
try {
base.evaluate();
}
finally {
after();
}
}
}, description);
}
public ConcurrentTestExceptionStatement(Statement originalStatement) {
testStatement = originalStatement;
ConcurrentTestExceptionHandler.clear();
// enable timeout monitor by default; disable to permit extended debugging when running
// from eclipse or when set via a system property
if (ignoreTimeout()) {
timoutMonitor = null;
}
else {
long testTimeout = getTestTimeout();
timoutMonitor = GTimer.scheduleRunnable(testTimeout, () -> {
// no-op; we will use the monitor directly
});
}
}
public Statement apply(final Statement base, FrameworkMethod method, Object target) {
final String sampleName = getSampleName(method);
sampleDir = sampleName == null ? null : testDirectoryProvider.getTestDirectory().file(sampleName);
return new Statement() {
@Override
public void evaluate() throws Throwable {
if (sampleName != null) {
TestFile srcDir = new IntegrationTestBuildContext().getSamplesDir().file(sampleName).assertIsDir();
logger.debug("Copying sample '{}' to test directory.", sampleName);
srcDir.copyTo(sampleDir);
} else {
logger.debug("No sample specified for this test, skipping.");
}
base.evaluate();
}
};
}
public Statement apply(final Statement base, FrameworkMethod method, Object target) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
originalStdOut = System.out;
originalStdErr = System.err;
try {
System.setOut(stdOutPrintStream);
System.setErr(stdErrPrintStream);
base.evaluate();
} finally {
System.setOut(originalStdOut);
System.setErr(originalStdErr);
stdOutPrintStream = null;
stdErrPrintStream = null;
stdoutContent = null;
stderrContent = null;
}
}
};
}
/**
* Implementation based on {@link TestWatcher}.
*/
@Override
public Statement apply(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
List<Throwable> errors = new ArrayList<Throwable>();
startingQuietly(description, errors);
try {
base.evaluate();
succeededQuietly(description, errors);
} catch (AssumptionViolatedException e) {
errors.add(e);
skippedQuietly(e, description, errors);
} catch (Throwable t) {
errors.add(t);
failedQuietly(t, description, errors);
} finally {
finishedQuietly(description, errors);
}
MultipleFailureException.assertEmpty(errors);
}
};
}
/**
* Called when used as a jUnit Rule.
*/
@Override
public Statement apply(Statement statement, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
// Override the settings
override();
try {
// Execute the test
statement.evaluate();
} finally {
// Restore the old settings
restore();
}
}
};
}
@Override
default Statement apply(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
before();
try {
base.evaluate();
} catch (final Throwable testThrowable) {
try {
afterTestFailure();
} catch (final Throwable afterFailureThrowable) {
testThrowable.addSuppressed(afterFailureThrowable);
}
throw testThrowable;
}
afterTestSuccess();
}
};
}
@Override
protected Statement withAfterClasses(Statement statement) {
List<FrameworkMethod> afters = wrapInWebTauTestEntry(getTestClass()
.getAnnotatedMethods(AfterClass.class));
return afters.isEmpty() ? statement :
new RunAfters(statement, afters, null);
}
@Override
protected Statement withBeforeClasses(Statement statement) {
List<FrameworkMethod> befores = wrapInWebTauTestEntry(getTestClass()
.getAnnotatedMethods(BeforeClass.class));
return befores.isEmpty() ? statement :
new RunBefores(statement, befores, null);
}
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
base.evaluate();
em.clear();
}
};
}
protected Statement withColaBefores(FrameworkMethod method, Object target,
Statement statement) {
List<FrameworkMethod> befores = getTestClass().getAnnotatedMethods(
ColaBefore.class);
return befores.isEmpty() ? statement : new RunBefores(statement,
befores, target);
}
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@SuppressWarnings("unchecked")
@Override
public void evaluate() throws Throwable {
resetSubscriberMock();
base.evaluate();
}
};
}
public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
init(method.getName(), target.getClass().getSimpleName());
return new Statement() {
@Override
public void evaluate() throws Throwable {
base.evaluate();
getTestDirectory().maybeDeleteDir();
// Don't delete on failure
}
};
}
@Override
public Statement apply(Statement statement, Description description) {
RetryOnFailure retryOnFailure = description.getAnnotation(RetryOnFailure.class);
RetryOnException retryOnException = description.getAnnotation(RetryOnException.class);
// sanity check that we don't use expected exceptions with the RetryOnX annotations
if (retryOnFailure != null || retryOnException != null) {
Test test = description.getAnnotation(Test.class);
if (test.expected() != Test.None.class) {
throw new IllegalArgumentException("You cannot combine the RetryOnFailure " +
"annotation with the Test(expected) annotation.");
}
}
// sanity check that we don't use both annotations
if (retryOnFailure != null && retryOnException != null) {
throw new IllegalArgumentException(
"You cannot combine the RetryOnFailure and RetryOnException annotations.");
}
if (retryOnFailure != null) {
return new RetryOnFailureStatement(retryOnFailure.times(), statement);
}
else if (retryOnException != null) {
return new RetryOnExceptionStatement(retryOnException.times(), retryOnException.exception(), statement);
}
else {
return statement;
}
}
public Statement apply(Statement base, final FrameworkMethod method, Object target) {
final Statement statement = resources.apply(base, method, target);
return new Statement() {
@Override
public void evaluate() throws Throwable {
String className = method.getMethod().getDeclaringClass().getSimpleName();
maybeCopy(String.format("%s/shared", className));
maybeCopy(String.format("%s/%s", className, method.getName()));
for (String extraResource : extraResources) {
maybeCopy(extraResource);
}
statement.evaluate();
}
};
}
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
if (dbEngine == DatabaseEngine.ORACLE) {
base.evaluate();
} else {
throw new AssumptionViolatedException(
"Current database engine is " + dbEngine.toString() +
", test requires ORACLE. Skipping");
}
}
};
}
@Override
public Statement apply(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
TestTopologyRule.this.start();
try {
base.evaluate();
} finally {
TestTopologyRule.this.stop();
}
}
};
}
@Override
public Statement apply(Statement base, Description description) {
boolean ignoreCodegen = description.getAnnotation(IgnoreCodegen.class) != null;
if (ignoreCodegen && backend == Backend.CODEGEN) {
return new Statement() {
@Override
public void evaluate() {
throw new AssumptionViolatedException("Ignored in code gen backend");
}
};
}
ReflectBug reflectBug = description.getAnnotation(ReflectBug.class);
if (reflectBug != null && backend == Backend.REFLECT) {
return new Statement() {
@Override
public void evaluate() {
try {
base.evaluate();
} catch (Throwable t) {
String message = "Known issue in reflection backend";
if (!reflectBug.value().isEmpty()) {
message += ": " + reflectBug.value();
}
throw new AssumptionViolatedException(message, t);
}
throw new AssertionError("Test succeeded when expected to fail. Remove @ReflectBug?");
}
};
}
return base;
}
public MainJvmAfterJUnitStatement(
FrameworkMethod frameworkMethod
, TestExecutionContext testExecutionContext
, QuickPerfConfigs quickPerfConfigs
, Statement junitAfters) {
this.testExecutionContext = testExecutionContext;
this.frameworkMethod = frameworkMethod;
this.testAnnotationConfigs = quickPerfConfigs.getTestAnnotationConfigs();
this.junitAfters = junitAfters;
}
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
String methodName = description.getMethodName();
System.out.println(methodName + "测试开始~");
//执行单元测试操作
base.evaluate();
System.out.println(methodName + "测试结束");
}
};
}
@Override
public Statement apply(Statement base, FrameworkMethod method, Object target) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try (KafkaServerScope scope = new KafkaServerScope(requiresKafkaServer(method))) {
base.evaluate();
}
}
};
}
public Statement apply(Statement base, Description description) {
return new FailOnTimeout(base, MIN_TIMEOUT) {
@Override
public void evaluate() throws Throwable {
try {
super.evaluate();
throw new TimeoutException();
} catch (Exception e) {
}
}
};
}
@Test
public void multiResource_cleanupGracefully() throws Throwable {
// setup
Resource resource1 = mock(Resource.class);
Resource resource2 = mock(Resource.class);
Resource resource3 = mock(Resource.class);
doReturn(true).when(resource1).awaitReleased(anyLong(), any(TimeUnit.class));
doReturn(true).when(resource2).awaitReleased(anyLong(), any(TimeUnit.class));
doReturn(true).when(resource3).awaitReleased(anyLong(), any(TimeUnit.class));
Statement statement = mock(Statement.class);
InOrder inOrder = inOrder(statement, resource1, resource2, resource3);
GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
// run
grpcCleanup.register(resource1);
grpcCleanup.register(resource2);
grpcCleanup.register(resource3);
grpcCleanup.apply(statement, null /* description*/).evaluate();
// Verify.
inOrder.verify(statement).evaluate();
inOrder.verify(resource3).cleanUp();
inOrder.verify(resource2).cleanUp();
inOrder.verify(resource1).cleanUp();
inOrder.verify(resource3).awaitReleased(anyLong(), any(TimeUnit.class));
inOrder.verify(resource2).awaitReleased(anyLong(), any(TimeUnit.class));
inOrder.verify(resource1).awaitReleased(anyLong(), any(TimeUnit.class));
inOrder.verifyNoMoreInteractions();
verify(resource1, never()).forceCleanUp();
verify(resource2, never()).forceCleanUp();
verify(resource3, never()).forceCleanUp();
}
@Test
public void multiResource_timeoutCalculation() throws Throwable {
// setup
Resource resource1 = mock(FakeResource.class,
delegatesTo(new FakeResource(1 /* cleanupNanos */, 10 /* awaitReleaseNanos */)));
Resource resource2 = mock(FakeResource.class,
delegatesTo(new FakeResource(100 /* cleanupNanos */, 1000 /* awaitReleaseNanos */)));
Statement statement = mock(Statement.class);
InOrder inOrder = inOrder(statement, resource1, resource2);
GrpcCleanupRule grpcCleanup = new GrpcCleanupRule().setTicker(fakeClock.getTicker());
// run
grpcCleanup.register(resource1);
grpcCleanup.register(resource2);
grpcCleanup.apply(statement, null /* description*/).evaluate();
// verify
inOrder.verify(statement).evaluate();
inOrder.verify(resource2).cleanUp();
inOrder.verify(resource1).cleanUp();
inOrder.verify(resource2).awaitReleased(
TimeUnit.SECONDS.toNanos(10) - 100 - 1, TimeUnit.NANOSECONDS);
inOrder.verify(resource1).awaitReleased(
TimeUnit.SECONDS.toNanos(10) - 100 - 1 - 1000, TimeUnit.NANOSECONDS);
inOrder.verifyNoMoreInteractions();
verify(resource2, never()).forceCleanUp();
verify(resource1, never()).forceCleanUp();
}
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
if (dbEngine == DatabaseEngine.POSTGRES) {
base.evaluate();
} else {
throw new AssumptionViolatedException(
"Current database engine is " + dbEngine.toString() +
", test requires POSTGRES. Skipping");
}
}
};
}
private RetryOnFailureStatement(int timesOnFailure, Statement statement) {
if (timesOnFailure < 0) {
throw new IllegalArgumentException("Negatives number of retries on failure");
}
this.timesOnFailure = timesOnFailure;
this.statement = statement;
}
/**
* Wrap the supplied {@link Statement} with a {@code RunAfterTestMethodCallbacks} statement.
* @see RunAfterTestMethodCallbacks
*/
private Statement withAfterTestMethodCallbacks(Statement next, Method testMethod,
Object testInstance, TestContextManager testContextManager) {
return new RunAfterTestMethodCallbacks(
next, testInstance, testMethod, testContextManager);
}
@Override
public Statement apply(Statement base, Description description) {
// Check if multiple Timeout are present and annotated with @Rule.
Class<?> clazz = description.getTestClass();
List<Class<?>> timeoutRuleClasses = new ArrayList<>(2);
do {
for (Field field : clazz.getDeclaredFields()) {
if (field.isAnnotationPresent(Rule.class) && Timeout.class.isAssignableFrom(field.getType())) {
timeoutRuleClasses.add(clazz);
}
}
} while ((clazz = clazz.getSuperclass()) != Object.class);
if (timeoutRuleClasses.size() > 1) {
StringBuilder sb = new StringBuilder(256)
.append("Only one @Rule for a Timeout is allowed, but ")
.append(timeoutRuleClasses.size())
.append(" were detected in types: ");
for (Class<?> clazz2 : timeoutRuleClasses) {
sb.append(clazz2.getName()).append(", ");
}
sb.setLength(sb.length() - 2);
throw new IllegalStateException(sb.toString());
}
// If timeout is specified in @Test, let that have precedence over the global timeout.
Test testAnnotation = description.getAnnotation(Test.class);
if (testAnnotation != null) {
long timeout = testAnnotation.timeout();
if (timeout > 0) {
return new TimeoutStatement(base, timeout, TimeUnit.MILLISECONDS, onTimeout);
}
}
return new TimeoutStatement(base, getTimeout(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS, onTimeout);
}
@Override
public Statement apply(Statement statement, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
applications.clear(); // 在测例执行前清空一次Registry数据
statement.evaluate();
}
};
}