下面列出了怎么用org.junit.rules.TestRule的API类实例代码及写法,或者点击链接到github查看源代码。
private TestRule getHiveRunnerConfigRule(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;
}
};
}
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();
}
});
}
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();
}
});
}
/**
* @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;
}
public TestRule createTestRule() {
return new ExternalResource() {
ResteasyServerBootstrap bootstrap = new ResteasyServerBootstrap(jaxRsApplication);
protected void before() throws Throwable {
bootstrap.start();
}
protected void after() {
bootstrap.stop();
}
};
}
@Override
protected List<TestRule> classRules() {
if (SystemProperties.TEST_CODE_EXECUTING_IN_NEW_JVM.evaluate()) {
return QUICK_PERF_SPRING_RUNNER_FOR_SPECIFIC_JVM.classRules();
}
if(quickPerfFeaturesAreDisabled) {
return springRunner.classRules();
}
return super.classRules();
}
/**
* Creates a {@link RuleChain} where the rules are evaluated in the order you pass in.
*
* @param testRules
* test rules to evaluate
* @return a new rule chain.
*/
public static RuleChain create(final TestRule... testRules) {
if (testRules == null || testRules.length == 0) {
return RuleChain.emptyRuleChain();
}
RuleChain ruleChain = RuleChain.outerRule(testRules[0]);
for (int i = 1; i < testRules.length; i++) {
ruleChain = ruleChain.around(testRules[i]);
}
return ruleChain;
}
public static TestRule create(final HiveRunnerConfig config, final Object target) {
return new TestRule() {
@Override
public Statement apply(Statement base, Description description) {
return new ThrowOnTimeout(base, config, target);
}
};
}
public TestRule createTestRule() {
return new ExternalResource() {
JerseyServerBootstrap bootstrap = new JerseyServerBootstrap(jaxRsApplication);
protected void before() throws Throwable {
bootstrap.start();
}
protected void after() {
bootstrap.stop();
}
};
}
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;
}
@Override
protected List<TestRule> getTestRules(Object target) {
if (SystemProperties.TEST_CODE_EXECUTING_IN_NEW_JVM.evaluate()) {
return QUICK_PERF_SPRING_RUNNER_FOR_SPECIFIC_JVM.getTestRules(target);
}
if(quickPerfFeaturesAreDisabled) {
return springRunner.getTestRules(target);
}
return super.getTestRules(target);
}
@Override
protected List<TestRule> classRules() {
final TemporaryFolder temporaryFolder = new TemporaryFolder();
try {
hmsPort = HiveTestUtils.getFreePort();
} catch (IOException e) {
throw new RuntimeException(e);
}
HiveServerContext context = new FlinkStandaloneHiveServerContext(temporaryFolder, config, hmsPort);
List<TestRule> rules = super.classRules();
ExternalResource hms = new ExternalResource() {
@Override
protected void before() throws Throwable {
LOGGER.info("Setting up {} in {}", getName(), temporaryFolder.getRoot().getAbsolutePath());
hmsWatcher = startHMS(context, hmsPort);
}
@Override
protected void after() {
if (hmsWatcher != null) {
hmsWatcher.cancel(true);
}
}
};
ExternalResource hiveShell = new ExternalResource() {
@Override
protected void before() throws Throwable {
container = createHiveServerContainer(getTestClass().getJavaClass(), context);
}
@Override
protected void after() {
tearDown();
}
};
rules.add(hiveShell);
rules.add(hms);
rules.add(temporaryFolder);
return rules;
}
private Statement withMethodRules(final FrameworkMethod method, final Object target, Statement result) {
final List<TestRule> testRules = getTestRules(target);
for (final org.junit.rules.MethodRule each : getMethodRules(target)) {
if (!testRules.contains(each)) {
result = each.apply(result, method, target);
}
}
return result;
}
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;
}
/**
* 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(final 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");
}
/**
* 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();
}
};
}
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);
}
static void executeTestThatThrowsExceptionWithRule(
Statement test,
TestRule rule
) {
ignoreException(
executeTestWithRuleRaw(test, rule),
Throwable.class
);
}
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();
}
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()));
}
}
public TestRule getTestRule(Class<?> testClass) {
TestRuleFactory ruleFactory = DEFAULT_RULE_FACTORY;
if (TEST_RULE_FACTORIES.containsKey(testClass)) {
ruleFactory = TEST_RULE_FACTORIES.get(testClass);
}
return ruleFactory.createTestRule();
}
public TestRule createTestRule() {
return new ExternalResource() {
JerseyServerBootstrap bootstrap = new JerseyServerBootstrap(jaxRsApplication);
protected void before() throws Throwable {
bootstrap.start();
}
protected void after() {
bootstrap.stop();
}
};
}
@Override
protected List<TestRule> getTestRules(final Object target) {
final List<TestRule> rules = new ArrayList<TestRule>();
rules.add(new InjectRule(target, startingStatement));
rules.add(new TransactionRule());
rules.addAll(getTestClass().getAnnotatedFieldValues(target, Rule.class, TestRule.class));
return rules;
}
public TestRule getTestRule(Class<?> testClass) {
TestRuleFactory ruleFactory = DEFAULT_RULE_FACTORY;
if (TEST_RULE_FACTORIES.containsKey(testClass)) {
ruleFactory = TEST_RULE_FACTORIES.get(testClass);
}
return ruleFactory.createTestRule();
}
/**
* Creates a test rule.
*
* @return a test rule.
*/
@Rule
public TestRule rule() {
return RuleChain
.outerRule(new LogbackAccessEventQueuingAppenderRule())
.around(new LogbackAccessEventQueuingListenerRule());
}
/**
* Creates a test rule.
*
* @return a test rule.
*/
@Rule
public TestRule rule() {
return RuleChain
.outerRule(new LogbackAccessEventQueuingAppenderRule())
.around(new LogbackAccessEventQueuingListenerRule());
}
/**
* Creates a test rule.
*
* @return a test rule.
*/
@Rule
public TestRule rule() {
return RuleChain
.outerRule(new LogbackAccessEventQueuingAppenderRule())
.around(new LogbackAccessEventQueuingListenerRule());
}
private <ATR extends ApplicativeTestRule<JenkinsInstance>> List<TestRule> instantiated(List<ATR> rules) {
List<TestRule> instantiatedRules = new ArrayList<>(rules.size());
for (ATR testRule : rules) {
instantiatedRules.add(testRule.applyTo(this));
}
return instantiatedRules;
}
/**
* Creates a test rule.
*
* @return a test rule.
*/
@Rule
public TestRule rule() {
return RuleChain
.outerRule(new LogbackAccessEventQueuingAppenderRule())
.around(new LogbackAccessEventQueuingListenerRule());
}
@Override
protected List<TestRule> getTestRules(Object target) {
AnnotationsHandlerRule rule = new AnnotationsHandlerRule(target, server, configuration);
log.debug("Injecting {} to test rules", rule);
List<TestRule> testRules = super.getTestRules(target);
testRules.add(rule);
return testRules;
}