org.junit.runners.model.Statement Java Examples

The following examples show how to use org.junit.runners.model.Statement. 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 File: ActivitiRule.java    From activiti6-boot2 with 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 File: ActivitiFormRule.java    From activiti6-boot2 with 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 #3
Source File: Sample.java    From pushfish-android with 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 #4
Source File: SettingsOverride.java    From gcp-token-broker with 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 #5
Source File: ExternalResource.java    From flink with 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 #6
Source File: GradleBuild.java    From spring-javaformat with 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 #7
Source File: ConcurrentTestExceptionStatement.java    From ghidra with 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 #8
Source File: RedirectStdOutAndErr.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 #9
Source File: MyRuler.java    From Awesome-WanAndroid with 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 #10
Source File: WebTauRunner.java    From webtau with 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 #11
Source File: BCryptHighCostTest.java    From bcrypt with 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 #12
Source File: KafkaServerRule.java    From kafka-workers with 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 #13
Source File: LegacyMockedSingleListenerRule.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Override
public Statement apply(Statement base, Description description) {
    return new Statement() {
        @SuppressWarnings("unchecked")
        @Override
        public void evaluate() throws Throwable {
            resetSubscriberMock();
            base.evaluate();
        }
    };
}
 
Example #14
Source File: MainJvmAfterJUnitStatement.java    From quickperf with 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 #15
Source File: IntegrationTestRule.java    From dagger-reflect with 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 #16
Source File: TestNameTestDirectoryProvider.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 #17
Source File: ColaTestUnitRunner.java    From COLA with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #18
Source File: GrpcCleanupRuleTest.java    From grpc-nebula-java with 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 #19
Source File: GrpcCleanupRuleTest.java    From grpc-nebula-java with 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 #20
Source File: AssumingPostgresEngine.java    From OpenCue with 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 #21
Source File: RetryRule.java    From Flink-CEPplus with 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 #22
Source File: SpringMethodRule.java    From java-technology-stack with 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 #23
Source File: ServiceTalkTestTimeout.java    From servicetalk with 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 #24
Source File: MockRegistry.java    From sofa-dashboard with 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();
        }
    };
}
 
Example #25
Source File: SpringMethodRule.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Wrap the supplied {@link Statement} with a {@code RunBeforeTestMethodCallbacks} statement.
 * @see RunBeforeTestMethodCallbacks
 */
private Statement withBeforeTestMethodCallbacks(Statement next, Method testMethod,
		Object testInstance, TestContextManager testContextManager) {

	return new RunBeforeTestMethodCallbacks(
			next, testInstance, testMethod, testContextManager);
}
 
Example #26
Source File: RetryRule.java    From flink with Apache License 2.0 5 votes vote down vote up
private RetryOnExceptionStatement(int timesOnFailure, Class<? extends Throwable> exceptionClass, Statement statement) {
	if (timesOnFailure < 0) {
		throw new IllegalArgumentException("Negatives number of retries on failure");
	}
	if (exceptionClass == null) {
		throw new NullPointerException("exceptionClass");
	}

	this.exceptionClass = (exceptionClass);
	this.timesOnFailure = timesOnFailure;
	this.statement = statement;
}
 
Example #27
Source File: SpringJUnit4ParameterizedClassRunner.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Augments the default JUnit behavior
 * {@link #withPotentialRepeat(FrameworkMethod, Object, Statement) with
 * potential repeats} of the entire execution chain.
 * <p>
 * Furthermore, support for timeouts has been moved down the execution chain
 * in order to include execution of {@link org.junit.Before &#064;Before}
 * and {@link org.junit.After &#064;After} methods within the timed
 * execution. Note that this differs from the default JUnit behavior of
 * executing <code>&#064;Before</code> and <code>&#064;After</code> methods
 * in the main thread while executing the actual test method in a separate
 * thread. Thus, the end effect is that <code>&#064;Before</code> and
 * <code>&#064;After</code> methods will be executed in the same thread as
 * the test method. As a consequence, JUnit-specified timeouts will work
 * fine in combination with Spring transactions. Note that JUnit-specific
 * timeouts still differ from Spring-specific timeouts in that the former
 * execute in a separate thread while the latter simply execute in the main
 * thread (like regular tests).
 * </p>
 *
 * @see #possiblyExpectingExceptions(FrameworkMethod, Object, Statement)
 * @see #withBefores(FrameworkMethod, Object, Statement)
 * @see #withAfters(FrameworkMethod, Object, Statement)
 * @see #withPotentialTimeout(FrameworkMethod, Object, Statement)
 * @see #withPotentialRepeat(FrameworkMethod, Object, Statement)
 */
@Override
protected Statement methodBlock(FrameworkMethod frameworkMethod) {

  Object testInstance;
  try {
    testInstance = new ReflectiveCallable() {

      @Override
      protected Object runReflectiveCall() throws Throwable {
        return createTest();
      }
    }.run();
  } catch (Throwable e) {
    return new Fail(e);
  }

  Statement statement = methodInvoker(frameworkMethod, testInstance);
  statement = possiblyExpectingExceptions(frameworkMethod, testInstance, statement);
  statement = withRulesReflectively(frameworkMethod, testInstance, statement);
  statement = withBefores(frameworkMethod, testInstance, statement);
  statement = withAfters(frameworkMethod, testInstance, statement);
  statement = withPotentialRepeat(frameworkMethod, testInstance, statement);
  statement = withPotentialTimeout(frameworkMethod, testInstance, statement);

  return statement;
}
 
Example #28
Source File: RepeatRule.java    From bcrypt with Apache License 2.0 5 votes vote down vote up
@Override
public Statement apply(Statement statement, Description description) {
    Statement result = statement;
    Repeat repeat = description.getAnnotation(Repeat.class);
    if (repeat != null) {
        int times = repeat.value();
        result = new RepeatStatement(statement, times);
    }
    return result;
}
 
Example #29
Source File: RepeatRule.java    From aion with MIT License 5 votes vote down vote up
@Override
public Statement apply(Statement statement, Description description) {
    Statement result = statement;
    Repeat repeat = description.getAnnotation(Repeat.class);
    if (repeat != null) {
        int times = repeat.value();
        result = new RepeatStatement(statement, times);
    }
    return result;
}
 
Example #30
Source File: RetryRule.java    From flink with 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;
}