Java Code Examples for org.junit.runners.model.Statement

The following examples show how to use org.junit.runners.model.Statement. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: activiti6-boot2   Source File: ActivitiFormRule.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
  };
}
 
Example 2
Source Project: spring-javaformat   Source File: GradleBuild.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 3
Source Project: ghidra   Source File: ConcurrentTestExceptionStatement.java    License: Apache License 2.0 6 votes vote down vote up
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
		});
	}
}
 
Example 4
Source Project: pushfish-android   Source File: Sample.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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();
        }
    };
}
 
Example 5
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;
            }
        }
    };
}
 
Example 6
Source Project: activiti6-boot2   Source File: ActivitiRule.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
  };
}
 
Example 7
Source Project: gcp-token-broker   Source File: SettingsOverride.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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();
            }
        }
    };
}
 
Example 8
Source Project: flink   Source File: ExternalResource.java    License: Apache License 2.0 6 votes vote down vote up
@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();
		}
	};
}
 
Example 9
Source Project: webtau   Source File: WebTauRunner.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Statement withAfterClasses(Statement statement) {
    List<FrameworkMethod> afters = wrapInWebTauTestEntry(getTestClass()
            .getAnnotatedMethods(AfterClass.class));
    return afters.isEmpty() ? statement :
            new RunAfters(statement, afters, null);
}
 
Example 10
Source Project: webtau   Source File: WebTauRunner.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Statement withBeforeClasses(Statement statement) {
    List<FrameworkMethod> befores = wrapInWebTauTestEntry(getTestClass()
            .getAnnotatedMethods(BeforeClass.class));
    return befores.isEmpty() ? statement :
            new RunBefores(statement, befores, null);
}
 
Example 11
Source Project: blog-tutorials   Source File: EntityManagerProvider.java    License: MIT License 5 votes vote down vote up
@Override
public Statement apply(Statement base, Description description) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            base.evaluate();
            em.clear();
        }

    };
}
 
Example 12
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);
}
 
Example 13
@Override
public Statement apply(Statement base, Description description) {
    return new Statement() {
        @SuppressWarnings("unchecked")
        @Override
        public void evaluate() throws Throwable {
            resetSubscriberMock();
            base.evaluate();
        }
    };
}
 
Example 14
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
        }
    };
}
 
Example 15
Source Project: Flink-CEPplus   Source File: RetryRule.java    License: Apache License 2.0 5 votes vote down vote up
@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;
	}
}
 
Example 16
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();
        }
    };
}
 
Example 17
Source Project: OpenCue   Source File: AssumingOracleEngine.java    License: Apache License 2.0 5 votes vote down vote up
@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");
            }
        }
    };
}
 
Example 18
Source Project: fluent-kafka-streams-tests   Source File: TestTopologyRule.java    License: MIT License 5 votes vote down vote up
@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();
            }
        }
    };
}
 
Example 19
Source Project: dagger-reflect   Source File: IntegrationTestRule.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 20
Source Project: quickperf   Source File: MainJvmAfterJUnitStatement.java    License: Apache License 2.0 5 votes vote down vote up
public MainJvmAfterJUnitStatement(
          FrameworkMethod frameworkMethod
        , TestExecutionContext testExecutionContext
        , QuickPerfConfigs quickPerfConfigs
        , Statement junitAfters) {
    this.testExecutionContext = testExecutionContext;
    this.frameworkMethod = frameworkMethod;
    this.testAnnotationConfigs = quickPerfConfigs.getTestAnnotationConfigs();
    this.junitAfters = junitAfters;
}
 
Example 21
Source Project: Awesome-WanAndroid   Source File: MyRuler.java    License: Apache License 2.0 5 votes vote down vote up
@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 + "测试结束");
        }
    };
}
 
Example 22
Source Project: kafka-workers   Source File: KafkaServerRule.java    License: Apache License 2.0 5 votes vote down vote up
@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();
            }
        }
    };
}
 
Example 23
Source Project: bcrypt   Source File: BCryptHighCostTest.java    License: Apache License 2.0 5 votes vote down vote up
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) {
            }
        }
    };
}
 
Example 24
Source Project: grpc-nebula-java   Source File: GrpcCleanupRuleTest.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 25
Source Project: grpc-nebula-java   Source File: GrpcCleanupRuleTest.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 26
Source Project: OpenCue   Source File: AssumingPostgresEngine.java    License: Apache License 2.0 5 votes vote down vote up
@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");
            }
        }
    };
}
 
Example 27
Source Project: Flink-CEPplus   Source File: RetryRule.java    License: Apache License 2.0 5 votes vote down vote up
private RetryOnFailureStatement(int timesOnFailure, Statement statement) {
	if (timesOnFailure < 0) {
		throw new IllegalArgumentException("Negatives number of retries on failure");
	}
	this.timesOnFailure = timesOnFailure;
	this.statement = statement;
}
 
Example 28
Source Project: java-technology-stack   Source File: SpringMethodRule.java    License: MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example 29
Source Project: servicetalk   Source File: ServiceTalkTestTimeout.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 30
Source Project: sofa-dashboard   Source File: MockRegistry.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Statement apply(Statement statement, Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            applications.clear(); // 在测例执行前清空一次Registry数据
            statement.evaluate();
        }
    };
}