下面列出了org.junit.runner.Description#getAnnotation() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void prepareIgnoreMessage(Description description, boolean commentMessage) {
Map attrs = new HashMap();
if (commentMessage) {
try {
final Ignore ignoredAnnotation = (Ignore)description.getAnnotation(Ignore.class);
if (ignoredAnnotation != null) {
final String val = ignoredAnnotation.value();
if (val != null) {
attrs.put("message", val);
}
}
}
catch (NoSuchMethodError ignored) {
//junit < 4.4
}
}
attrs.put("name", getMethodName(description));
System.out.println(ServiceMessage.asString(ServiceMessageTypes.TEST_IGNORED, attrs));
}
@Override
protected void starting(Description description) {
if(description.getAnnotation(CmmnModelResource.class) != null) {
Class<?> testClass = description.getTestClass();
String methodName = description.getMethodName();
String resourceFolderName = testClass.getName().replaceAll("\\.", "/");
String cmmnResourceName = resourceFolderName + "." + methodName + ".cmmn";
InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(cmmnResourceName);
try {
CmmnModelInstance = Cmmn.readModelFromStream(resourceAsStream);
} finally {
IoUtil.closeSilently(resourceAsStream);
}
}
}
boolean hasJunitTimeout(Description description) {
// Do not do apply the default timeout if the test has its own @Test(timeout).
Test testAnnotation = description.getAnnotation(Test.class);
if (testAnnotation != null && testAnnotation.timeout() > 0) {
return true;
}
// Do not do apply the default timeout if the test has its own @Rule Timeout.
if (runner instanceof ParentRunner) {
return BuckBlockJUnit4ClassRunner.hasTimeoutRule(((ParentRunner) runner).getTestClass());
}
Class<?> clazz = description.getTestClass();
while (clazz != null) {
for (Field field : clazz.getFields()) {
if (field.getAnnotationsByType(Rule.class).length > 0
&& field.getType().equals(Timeout.class)) {
return true;
}
}
clazz = clazz.getSuperclass();
}
return false;
}
@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;
}
/**
* @return true if the test method in the {@link Description} is annotated with the test size
* annotation class.
*/
public boolean testMethodIsAnnotatedWithTestSize(Description description) {
if (description.getAnnotation(runnerFilterAnnotationClass) != null
|| description.getAnnotation(platformAnnotationClass) != null) {
// If the test method is annotated with a test size annotation include it
return true;
}
// Otherwise exclude it
return false;
}
@Override
protected void starting(Description d) {
final TargetVersions targetVersions = d.getAnnotation(TargetVersions.class);
if (targetVersions == null) return;
myMatcher = new CustomMatcher<String>("Gradle version '" + targetVersions.value() + "'") {
@Override
public boolean matches(Object item) {
return item instanceof String && new VersionMatcher(GradleVersion.version(item.toString())).isVersionMatch(targetVersions);
}
};
}
private static GradingSuite parseSuite(final Description description, final List<GradingTest> tests) {
final GradedCategory annotation = description.getAnnotation(GradedCategory.class);
final String suiteName =
annotation.name().equals(GradedTest.DEFAULT_NAME) ?
description.getDisplayName() : annotation.name();
final String suiteDescription =
annotation.description().equals(GradedTest.DEFAULT_DESCRIPTION) ?
null : annotation.description();
return new GradingSuite(description.getClassName(), suiteName, suiteDescription, tests);
}
@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(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
final RunAs annotation = description.getAnnotation(RunAs.class);
final As as = description.getAnnotation(As.class);
String currentRole = role.get();
role.remove(); // no more needed
if (annotation == null && as == null && currentRole == null) {
base.evaluate();
return;
}
final BeanContext beanContext = getBeanContext();
if (currentRole == null) {
if (annotation == null) {
currentRole = as.value();
} else {
currentRole = annotation.value();
}
}
final String runAs = beanContext.getRunAs();
final String runAsUser = beanContext.getRunAsUser();
beanContext.setRunAs(currentRole);
final ThreadContext old = ThreadContext.enter(new ThreadContext(beanContext, null));
try {
base.evaluate();
} finally {
// reset for next test
ThreadContext.exit(old);
beanContext.setRunAs(runAs);
beanContext.setRunAsUser(runAsUser);
}
}
};
}
public String
getIgnoredMessage(Description description) {
Ignore ignore = description.getAnnotation(Ignore.class
);
return ignore
== null || ignore.value()
.isEmpty() ? "Test ignored (without reason)!" : ignore.value();
}
@Override
public Statement apply(Statement base, Description description) {
final Flaky annotation = description.getAnnotation(Flaky.class);
if (annotation == null) {
// leave the statement as-is
return base;
}
if (annotation.githubIssueUrl().trim().length() == 0) {
throw new IllegalArgumentException("A GitHub issue URL must be set for usages of the @Flaky annotation");
}
final int maxTries = annotation.maxTries();
if (maxTries < 1) {
throw new IllegalArgumentException("@Flaky annotation maxTries must be at least one");
}
final LocalDate reviewDate;
try {
reviewDate = LocalDate.parse(annotation.reviewDate());
} catch (DateTimeParseException e) {
throw new IllegalArgumentException("@Flaky reviewDate could not be parsed. Please provide a date in yyyy-mm-dd format");
}
// the annotation should only have an effect before the review date, to encourage review and resolution
if ( LocalDate.now().isBefore(reviewDate) ) {
return new RetryingStatement(base, description, maxTries);
} else {
return base;
}
}
protected boolean shouldRunOnUiThread(Description description) {
if (description.getAnnotation(android.test.UiThreadTest.class) != null) {
Log.w(
TAG,
"Deprecated android.test.UiThreadTest annotation is used! please switch "
+ "to using androidx.test.annotation.UiThreadTest instead.");
return true;
}
return description.getAnnotation(UiThreadTest.class) != null;
}
private <T extends Annotation> List<T> getAnnotationsOnMethod(final Description result, final Class<T> clazz) {
final T annotation = result.getAnnotation(clazz);
return Stream.concat(
extractRepeatable(result, clazz).stream(),
Objects.isNull(annotation) ? Stream.empty() : Stream.of(annotation)
).collect(Collectors.toList());
}
@Override
public Statement apply(Statement statement, Description description) {
Repeat repeat = description.getAnnotation(Repeat.class);
if (repeat != null) {
statement = RepeatStatement.builder().build(repeat, statement);
}
return statement;
}
private SdkSuppress getAnnotationForTest(Description description) {
final SdkSuppress s = description.getAnnotation(SdkSuppress.class);
if (s != null) {
return s;
}
final Class<?> testClass = description.getTestClass();
if (testClass != null) {
return testClass.getAnnotation(SdkSuppress.class);
}
return null;
}
@Override
public Statement apply(Statement base, Description description) {
if (description.getTestClass().getAnnotation(IgnoreLeaks.class) != null
|| description.getAnnotation(IgnoreLeaks.class) != null) {
return base;
}
return new LambdaStatement(() -> {
ByteBufPool.clear();
base.evaluate();
assertEquals(ByteBufPool.getStats().getPoolItemsString(), ByteBufPool.getStats().getCreatedItems(), ByteBufPool.getStats().getPoolItems());
});
}
@Override
protected void starting(Description description) {
isStrictTest = description.getAnnotation(Strict.class) != null;
}
@Override
public void testStarted(final Description description) throws Exception {
final TestLogging testLogging = description.getAnnotation(TestLogging.class);
previousLoggingMap = processTestLogging(testLogging);
}
protected String getFileName(Description description) {
String methodName = description.getMethodName();
Video video = description.getAnnotation(Video.class);
return RecordingUtils.getVideoFileName(video,methodName);
}
public Statement apply(final Statement base, final Description description) {
if (description.getAnnotation(WithoutJenkins.class) != null) {
// request has been made to not create the instance for this test method
return base;
}
Statement wrapped = new Statement() {
@Override
public void evaluate() throws Throwable {
testDescription = description;
Thread t = Thread.currentThread();
String o = t.getName();
t.setName("Executing "+ testDescription.getDisplayName());
System.out.println("=== Starting " + testDescription.getDisplayName());
before();
try {
// so that test code has all the access to the system
ACL.impersonate(ACL.SYSTEM);
try {
base.evaluate();
} catch (Throwable th) {
// allow the late attachment of a debugger in case of a failure. Useful
// for diagnosing a rare failure
try {
throw new BreakException();
} catch (BreakException e) {}
RandomlyFails rf = testDescription.getAnnotation(RandomlyFails.class);
if (rf != null) {
System.err.println("Note: known to randomly fail: " + rf.value());
}
throw th;
}
} finally {
after();
testDescription = null;
t.setName(o);
}
}
};
final int testTimeout = getTestTimeoutOverride(description);
if (testTimeout <= 0) {
System.out.println("Test timeout disabled.");
return wrapped;
} else {
final Statement timeoutStatement = Timeout.seconds(testTimeout).apply(wrapped, description);
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
timeoutStatement.evaluate();
} catch (TestTimedOutException x) {
// withLookingForStuckThread does not work well; better to just have a full thread dump.
LOGGER.warning(String.format("Test timed out (after %d seconds).", testTimeout));
dumpThreads();
throw x;
}
}
};
}
}