Java 类org.junit.rules.TestRule 实例源码

项目:parameterized-suite    文件:BlockJUnit4ClassRunnerWithParametersUtil.java   
/**
 * Extends a given {@link Statement} for a {@link TestClass} with the evaluation of
 * {@link TestRule}, {@link ClassRule}, {@link Before} and {@link After}.
 * <p>
 * Therefore the test class will be instantiated and parameters will be injected with the same
 * mechanism as in {@link Parameterized}.
 * 
 * Implementation has been extracted from BlockJUnit4ClassRunner#methodBlock(FrameworkMethod).
 * 
 * @param baseStatementWithChildren - A {@link Statement} that includes execution of the test's
 *        children
 * @param testClass - The {@link TestClass} of the test.
 * @param description - The {@link Description} will be passed to the {@link Rule}s and
 *        {@link ClassRule}s.
 * @param singleParameter - The parameters will be injected in attributes annotated with
 *        {@link Parameterized.Parameter} or passed to the constructor otherwise.
 * 
 * @see BlockJUnit4ClassRunnerWithParameters#createTest()
 * @see BlockJUnit4ClassRunner#methodBlock(FrameworkMethod)
 */
public static Statement buildStatementWithTestRules(Statement baseStatementWithChildren, final TestClass testClass, Description description,
        final Object[] singleParameter) {
    final Object test;
    try {
        test = new ReflectiveCallable() {
            protected Object runReflectiveCall() throws Throwable {
                return createInstanceOfParameterizedTest(testClass, singleParameter);
            }
        }.run();
    } catch (Throwable e) {
        return new Fail(e);
    }

    List<TestRule> testRules = BlockJUnit4ClassRunnerUtil.getTestRules(test, testClass);
    Statement statement = BlockJUnit4ClassRunnerUtil.withTestRules(testRules, description, baseStatementWithChildren);

    statement = ParentRunnerUtil.withBeforeClasses(statement, testClass);
    statement = ParentRunnerUtil.withAfterClasses(statement, testClass);
    statement = ParentRunnerUtil.withClassRules(statement, testClass, description);
    return statement;
}
项目:powermock    文件:PowerMockJUnit49RunnerDelegateImpl.java   
@Override
protected Statement applyRuleToLastStatement(final Method method, final Object testInstance, Field field,
        final LastRuleTestExecutorStatement lastStatement) throws IllegalAccessException {
    final Object fieldValue = field.get(testInstance);
    final Statement statement;
    if (fieldValue instanceof MethodRule) {
        // the MethodRule is known by junit 4.9 -> delegate to super-class
        statement = super.applyRuleToLastStatement(method, testInstance, field, lastStatement);
    } else if (fieldValue instanceof TestRule){
        TestRule rule = (TestRule) fieldValue;
        statement = rule.apply(lastStatement, description);
    } else {
        throw new IllegalStateException("Can only handle MethodRule and TestRule");
    }
    return statement;
}
项目:rise    文件:WebTestBase.java   
@Rule
public final TestRule openAndCloseDriver() {
    return (base, description) -> new Statement() {

        @Override
        public void evaluate() throws Throwable {
            driver = createDriver();
            try {
                base.evaluate();
            } finally {
                if (closeDriver)
                    try {
                        driver.close();
                    } catch (Throwable t) {
                        // swallow
                    }
            }
        }
    };
}
项目:cloudera-framework    文件:TestRunner.java   
private Statement withLogging(final FrameworkMethod method, Object target, Statement statement) {
  final AtomicLong time = new AtomicLong();
  List<TestRule> rules = new ArrayList<>();
  rules.add(new ExternalResource() {
    @Override
    protected void before() throws Throwable {
      if (LOG.isDebugEnabled()) {
        time.set(System.currentTimeMillis());
        LOG.debug("Beginning [" + method.getDeclaringClass().getCanonicalName() + "." + method.getName() + "]");
      }
    }

    @Override
    protected void after() {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Completed [" + method.getDeclaringClass().getCanonicalName() + "." + method.getName() + "] in ["
          + (System.currentTimeMillis() - time.get()) + "] ms");
      }
    }
  });
  return new RunRules(statement, rules, getDescription());
}
项目:HiveRunner    文件:StandaloneHiveRunner.java   
private TestRule getHiveRunnerConfigRule(final Object target) {
    return new TestRule() {
        @Override
        public Statement apply(Statement base, Description description) {
            Set<Field> fields = ReflectionUtils.getAllFields(target.getClass(),
                    Predicates.and(
                            withAnnotation(HiveRunnerSetup.class),
                            withType(HiveRunnerConfig.class)));

            Preconditions.checkState(fields.size() <= 1,
                    "Exact one field of type HiveRunnerConfig should to be annotated with @HiveRunnerSetup");

            /*
             Override the config with test case config. Taking care to not replace the config instance since it
              has been passes around and referenced by some of the other test rules.
              */
            if (!fields.isEmpty()) {
                config.override(ReflectionUtils
                        .getFieldValue(target, fields.iterator().next().getName(), HiveRunnerConfig.class));
            }

            return base;
        }
    };
}
项目:vertx-junit-annotations    文件:JUnit4ClassRunnerAdapter.java   
@Override
protected List<TestRule> classRules() {
  List<TestRule> rules = super.classRules();
  rules.add(new ExternalResource() {
    @Override
    protected void before() throws Throwable {
      beforeClass();
      super.before();
    }

    @Override
    protected void after() {
      beforeAfterClass();
      super.after();
      afterClass();
    }
  });
  return rules;
}
项目:camunda-bpm-platform    文件:JerseySpecifics.java   
public TestRule createTestRule() {
  final TemporaryFolder tempFolder = new TemporaryFolder();

  return RuleChain
    .outerRule(tempFolder)
    .around(new ExternalResource() {

      TomcatServerBootstrap bootstrap = new JerseyTomcatServerBootstrap(webXmlResource);

      protected void before() throws Throwable {
        bootstrap.setWorkingDir(tempFolder.getRoot().getAbsolutePath());
        bootstrap.start();
      }

      protected void after() {
        bootstrap.stop();
      }
    });
}
项目:camunda-bpm-platform    文件:WinkSpecifics.java   
public TestRule createTestRule() {
  final TemporaryFolder tempFolder = new TemporaryFolder();

  return RuleChain
    .outerRule(tempFolder)
    .around(new ExternalResource() {

      WinkTomcatServerBootstrap bootstrap = new WinkTomcatServerBootstrap(webXmlResource);

      protected void before() throws Throwable {
        bootstrap.setWorkingDir(tempFolder.getRoot().getAbsolutePath());
        bootstrap.start();
      }

      protected void after() {
        bootstrap.stop();
      }
    });
}
项目:camunda-bpm-platform    文件:JerseySpecifics.java   
public TestRule createTestRule() {
  final TemporaryFolder tempFolder = new TemporaryFolder();

  return RuleChain
    .outerRule(tempFolder)
    .around(new ExternalResource() {

      TomcatServerBootstrap bootstrap = new JerseyTomcatServerBootstrap(webXmlResource);

      protected void before() throws Throwable {
        bootstrap.setWorkingDir(tempFolder.getRoot().getAbsolutePath());
        bootstrap.start();
      }

      protected void after() {
        bootstrap.stop();
      }
    });
}
项目:camunda-bpm-platform    文件:CXFSpecifics.java   
public TestRule createTestRule() {
  final TemporaryFolder tempFolder = new TemporaryFolder();

  return RuleChain
    .outerRule(tempFolder)
    .around(new ExternalResource() {

      TomcatServerBootstrap bootstrap = new CXFTomcatServerBootstrap(webXmlResource);

      protected void before() throws Throwable {
        bootstrap.setWorkingDir(tempFolder.getRoot().getAbsolutePath());
        bootstrap.start();
      }

      protected void after() {
        bootstrap.stop();
      }
    });
}
项目:camunda-bpm-platform    文件:ResteasySpecifics.java   
public TestRule createTestRule() {
  final TemporaryFolder tempFolder = new TemporaryFolder();

  return RuleChain
    .outerRule(tempFolder)
    .around(new ExternalResource() {

      ResteasyTomcatServerBootstrap bootstrap = new ResteasyTomcatServerBootstrap(webXmlResource);

      protected void before() throws Throwable {
        bootstrap.setWorkingDir(tempFolder.getRoot().getAbsolutePath());
        bootstrap.start();
      }

      protected void after() {
        bootstrap.stop();
      }
    });
}
项目:incubator-netbeans    文件:TestCatalogModel.java   
/**
 * A JUnit {@link TestRule} that stops tests from interfering with one 
 * another. JUnit will automatically set up/clean up the catalog when this
 * rule is used. <br/>
 * Usage:<br/>
 * {@code @Rule public final TestRule catalogMaintainer = TestCatalogModel.maintainer()}
 * @return the TestRule
 */
public static TestRule maintainer() {
    return new ExternalResource() {

        @Override
        protected void after() {
            getDefault().clearDocumentPool();
        }

    };
}
项目:Selenium-Foundation    文件:JUnitBase.java   
/**
 * Get the test rule of the specified type that's attached to the rule chain.
 * 
 * @param <T> test rule type
 * @param testRuleType test rule type
 * @return {@link ScreenshotCapture} test rule
 */
public <T extends TestRule> T getLinkedRule(Class<T> testRuleType) {
    Optional<T> optional = RuleChainWalker.getAttachedRule(ruleChain, testRuleType);
    if (optional.isPresent()) {
        return optional.get();
    }
    throw new IllegalStateException(testRuleType.getSimpleName() + " test rule wasn't found on the rule chain");
}
项目:io-comparison    文件:FocusRunner.java   
@Override
protected List<TestRule> getTestRules(Object target) {
    if (isFocusEnabled()) {
        List<TestRule> old = super.getTestRules(target);
        old.removeIf(rule -> rule instanceof Timeout);
        return old;
    } else {
        return super.getTestRules(target);
    }
}
项目:artifactory-resource    文件:ArtifactoryServerConnection.java   
private <R extends TestRule> Statement apply(Statement base, Description description,
        Delegate<R> delegate) {
    final R rule = delegate.createRule();
    Statement statement = new Statement() {

        @Override
        public void evaluate() throws Throwable {
            ArtifactoryServerConnection.this.serverFactory = (artifactory) -> delegate
                    .getArtifactoryServer(rule, artifactory);
            base.evaluate();
        }

    };
    return rule.apply(statement, description);
}
项目:monarch    文件:RuleList.java   
@Override
public Statement apply(Statement base, final Description description) {
  for (TestRule each : this.rules) {
    base = each.apply(base, description);
  }
  return base;
}
项目:easy-test    文件:EasyJUnit4.java   
private Statement withRules(FrameworkMethod method, Object target,
                            Statement statement) {
    List<TestRule> testRules = getTestRules(target);
    Statement result = statement;
    result = withMethodRules(method, testRules, target, result);
    result = withTestRules(method, testRules, result);

    return result;
}
项目:easy-test    文件:EasyJUnit4.java   
private Statement withMethodRules(FrameworkMethod method, List<TestRule> testRules,
                                  Object target, Statement result) {
    for (org.junit.rules.MethodRule each : getMethodRules(target)) {
        if (!testRules.contains(each)) {
            result = each.apply(result, method, target);
        }
    }
    return result;
}
项目:Avatar    文件:TestAvatarRuleWithBadCode.java   
@Test
public void testEvaluate_compilationFails_allowFailure() throws Throwable {
    final TestRule rule = AvatarRule
            .builder()
            .withSourceFileObjects(BAD_CODE)
            .withSuccessfulCompilationRequired(false)
            .build();

    evaluate(rule);
}
项目:Avatar    文件:TestAvatarRuleWithBadCode.java   
@Test(expected = RuntimeException.class)
public void testEvaluate_compilationFails_disallowFailure() throws Throwable {
    final TestRule rule = AvatarRule
            .builder()
            .withSourceFileObjects(BAD_CODE)
            .withSuccessfulCompilationRequired(true)
            .build();

    evaluate(rule);
}
项目:openjdk-jdk10    文件:NotOnDebug.java   
public static TestRule create(Timeout seconds) {
    try {
        return new DisableOnDebug(seconds);
    } catch (LinkageError ex) {
        return null;
    }
}
项目:bobcat    文件:TestRunner.java   
@Override
protected List<TestRule> getTestRules(Object target) {
  LOG.debug("adding additional rules for test: '{}'", target);
  List<TestRule> result = super.getTestRules(target);
  result.add(new ReportingRule(injector));
  result.add(new WebDriverClosingRule(injector));
  return result;
}
项目:grakn    文件:SessionContext.java   
@Override
protected List<TestRule> testRules() {
    if (GraknTestUtil.usingJanus()) {
        return ImmutableList.of(EmbeddedCassandraContext.create());
    } else {
        return ImmutableList.of();
    }
}
项目:grakn    文件:CompositeTestRule.java   
/**
 * Takes all the rules in {@link #testRules()} and applies them to this Test Rule.
 * This is essential because the composite rule may depend on these rules being executed.
 */
@Override
public final Statement apply(Statement base, Description description) {
    base = innerResource.apply(base, description);

    for (TestRule each : testRules()) {
        base = each.apply(base, description);
    }

    return base;
}
项目:grakn    文件:EngineContext.java   
@Override
protected final List<TestRule> testRules() {
    return ImmutableList.of(
            SessionContext.create(),
            redis
    );
}
项目:fake-sftp-server-rule    文件:Executor.java   
static void executeTestThatThrowsExceptionWithRule(
    Statement test,
    TestRule rule
) {
    ignoreException(
        executeTestWithRuleRaw(test, rule),
        Throwable.class
    );
}
项目:fake-sftp-server-rule    文件:Executor.java   
private static Statement executeTestWithRuleRaw(
    Statement test,
    TestRule rule
) {
    org.junit.runners.model.Statement statement
        = new org.junit.runners.model.Statement() {
            @Override
            public void evaluate() throws Throwable {
                test.evaluate();
            }
        };
    return () -> rule.apply(statement, DUMMY_DESCRIPTION).evaluate();
}
项目:video-recorder-java    文件:TestUtils.java   
public static void runRule(TestRule rule, Object target, String methodName) {
    Class<?> clazz = target.getClass();
    Method method = TestUtils.getMethod(clazz, methodName);
    Description description = Description.createTestDescription(clazz, method.getName(), method.getDeclaredAnnotations());
    try {
        InvokeMethod invokeMethod = new InvokeMethod(new FrameworkMethod(method), target);
        rule.apply(invokeMethod, description).evaluate();
    } catch (Throwable throwable) {
        logger.warning(Arrays.toString(throwable.getStackTrace()));
    }
}
项目:Camel    文件:CamelCdiRunner.java   
@Override
protected List<TestRule> classRules() {
    List<TestRule> rules = super.classRules();
    // Add the CDI container rule before all the other class rules
    // so that it's the last one in FIFO
    rules.add(0, new CamelCdiDeployment(getTestClass(), context));
    return rules;
}
项目:authrite    文件:SystemDriver.java   
public TestRule rules() {
    if (System.getProperty(ACCTEST_BASEURI_PROPERTY) == null) {
        return RuleChain
                .outerRule(databaseContext.rules())
                .around(appRule);
    } else {
        return new TestRule() {
            @Override
            public Statement apply(final Statement base, final Description description) {
                return base;
            }
        };
    }
}
项目:kc-rice    文件:LoadTimeWeavableTestRunner.java   
/**
 * @return the {@code ClassRule}s that can transform the block that runs
 *         each method in the tested class.
 */
protected List<TestRule> classRules() {
    List<TestRule> result = getTestClass().getAnnotatedMethodValues(null, ClassRule.class, TestRule.class);

    result.addAll(getTestClass().getAnnotatedFieldValues(null, ClassRule.class, TestRule.class));

    return result;
}
项目:kc-rice    文件:LoadTimeWeavableTestRunner.java   
private Statement withRules(FrameworkMethod method, Object target,
        Statement statement) {
    List<TestRule> testRules = getTestRules(target);
    Statement result = statement;
    result = withMethodRules(method, testRules, target, result);
    result = withTestRules(method, testRules, result);

    return result;
}
项目:kc-rice    文件:LoadTimeWeavableTestRunner.java   
private Statement withMethodRules(FrameworkMethod method, List<TestRule> testRules,
        Object target, Statement result) {
    for (org.junit.rules.MethodRule each : getMethodRules(target)) {
        if (!testRules.contains(each)) {
            result = each.apply(result, method, target);
        }
    }
    return result;
}
项目:kc-rice    文件:LoadTimeWeavableTestRunner.java   
/**
 * @param target the test case instance
 * @return a list of TestRules that should be applied when executing this
 *         test
 */
protected List<TestRule> getTestRules(Object target) {
    List<TestRule> result = getTestClass().getAnnotatedMethodValues(target,
            Rule.class, TestRule.class);

    result.addAll(getTestClass().getAnnotatedFieldValues(target,
            Rule.class, TestRule.class));

    return result;
}
项目:junit-volkswagen    文件:RunRules.java   
private static Statement applyAll(Statement result, Iterable<TestRule> rules,
        Description description) {
    for (TestRule each : rules) {
        try {
            result = each.apply(result, description);
        } catch (Exception e) {
            // Rules don't make errors, you silly
        }
    }
    return result;
}
项目:camunda-bpm-spring-boot-starter    文件:ProcessEngineRuleRunner.java   
@Override
protected List<TestRule> getTestRules(Object target) {
  List<TestRule> testRules = super.getTestRules(target);

  testRules.stream()
    .filter(t -> t instanceof ProcessEngineRule)
    .map(t -> (ProcessEngineRule)t)
    .forEach(processEngineRules::add);

  return testRules;
}
项目:junit-clptr    文件:ClassLoaderPerTestRunner.java   
@Override
protected synchronized List<TestRule> getTestRules(Object target)
{
    List<TestRule> result =
        testClassFromClassLoader
            .getAnnotatedMethodValues(target, (Class<? extends Annotation>) ruleFromClassLoader, TestRule.class);

    result.addAll(
        testClassFromClassLoader
            .getAnnotatedFieldValues(target, (Class<? extends Annotation>) ruleFromClassLoader, TestRule.class));

    return result;
}
项目:tool.lars    文件:ResourceFilteringTest.java   
/**
 * Create a RuleChain containing a RepositoryFixture for each of the repositories we are testing against
 *
 * @return a RuleChain
 */
@ClassRule
public static TestRule getClassRule() {
    // Put all the fixtures into one chain rule because we want to set up all the repositories at the start of the test, test with them and tear them down at the end
    RuleChain chain = RuleChain.emptyRuleChain();
    for (RepoData repoData : getRepoDataList()) {
        chain = chain.around(repoData.fixture);
    }
    return chain;
}
项目:logback-access-spring-boot-starter    文件:AbstractTestSpringConfigurationFileAutoDetectingTest.java   
/**
 * Creates a test rule.
 *
 * @return a test rule.
 */
@Rule
public TestRule rule() {
    return RuleChain
            .outerRule(new LogbackAccessEventQueuingAppenderRule())
            .around(new LogbackAccessEventQueuingListenerRule());
}
项目:logback-access-spring-boot-starter    文件:AbstractForwardHeadersUsingTest.java   
/**
 * Creates a test rule.
 *
 * @return a test rule.
 */
@Rule
public TestRule rule() {
    return RuleChain
            .outerRule(new LogbackAccessEventQueuingAppenderRule())
            .around(new LogbackAccessEventQueuingListenerRule());
}