下面列出了怎么用org.junit.runners.Suite的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* @return true if {@param cls} is {@link JUnit4} annotated.
*/
protected boolean isJUnit4TestClass(Class cls) {
// Need to find test classes, otherwise crashes with b/11790448.
if (!cls.getName().endsWith("Test")) {
return false;
}
// Check the annotations.
Annotation annotation = cls.getAnnotation(RunWith.class);
if (annotation != null) {
RunWith runWith = (RunWith) annotation;
Object value = runWith.value();
if (value.equals(JUnit4.class) || value.equals(Suite.class)) {
return true;
}
}
return false;
}
public static TestSuite getPackageTests(String pkgName) {
if (pkgName == null || pkgName.isEmpty()) {
throw new IllegalArgumentException("package name not specified");
}
Class<?>[] allJreTests = null;
try {
Class<?> allJreTestsClass = Class.forName("AllJreTests");
Annotation a = allJreTestsClass.getAnnotation(Suite.SuiteClasses.class);
if (a == null) {
throw new AssertionError(ALLJRETESTS_NOT_ACCESSIBLE);
}
Method valueAccessor = Suite.SuiteClasses.class.getDeclaredMethod("value");
allJreTests = (Class<?>[]) valueAccessor.invoke(a);
} catch (Exception e) {
throw new AssertionError(ALLJRETESTS_NOT_ACCESSIBLE);
}
TestSuite packageTests = new TestSuite();
for (Class<?> jreTest : allJreTests) {
Package testPackage = jreTest.getPackage();
if (testPackage != null && testPackage.getName().equals(pkgName) && !isSuiteClass(jreTest)) {
packageTests.addTest(new TestSuite(jreTest));
}
}
return packageTests;
}
private boolean isTestClass(Class<?> c) {
if (Modifier.isAbstract(c.getModifiers())) {
return false;
}
if (c.getAnnotation(Suite.SuiteClasses.class) != null) {
return true;
}
for (Method met : c.getMethods()) {
if (met.getAnnotation(Test.class) != null) {
return true;
}
}
return false;
}
/**
* Same verification than {@link #verifyTestList(Class)}, except that the set of base classes
* is explicitly specified. This method is preferred to {@code verifyTestList(Class)} only in
* the rare cases where some test cases need to extend something else than geoapi-conformance
* or Apache SIS test class.
*
* @param suite the suite for which to verify test order.
* @param baseTestClasses the set of base classes that all test cases are expected to extends.
*/
protected static void verifyTestList(final Class<? extends TestSuite> suite, final Class<?>[] baseTestClasses) {
final Class<?>[] testCases = suite.getAnnotation(Suite.SuiteClasses.class).value();
final Set<Class<?>> done = new HashSet<>(testCases.length);
for (final Class<?> testCase : testCases) {
if (!Classes.isAssignableToAny(testCase, baseTestClasses)) {
fail("Class " + testCase.getCanonicalName() + " does not extends TestCase.");
}
final DependsOn dependencies = testCase.getAnnotation(DependsOn.class);
if (dependencies != null) {
for (final Class<?> dependency : dependencies.value()) {
if (!done.contains(dependency)) {
fail("Class " + testCase.getCanonicalName() + " depends on " + dependency.getCanonicalName()
+ ", but the dependency has not been found before the test.");
}
}
}
if (!done.add(testCase)) {
fail("Class " + testCase.getCanonicalName() + " is declared twice.");
}
}
}
private void handleJUnit4Suite(TypeElement typeElement) {
List<String> classes =
MoreApt.getClassNamesFromAnnotation(typeElement, Suite.SuiteClasses.class, "value");
if (classes.isEmpty()) {
errorReporter.report(ErrorMessage.EMPTY_SUITE, typeElement);
}
for (String clazzName : classes) {
TypeElement t = processingEnv.getElementUtils().getTypeElement(clazzName);
handleClass(t);
}
}
static Suite createSuite(List<Runner> runners) {
try {
return new ExtendedSuite(runners);
} catch (InitializationError e) {
throw new RuntimeException(
"Internal Error: "
+ Suite.class.getName()
+ "(Class<?>, List<Runner>) should never throw an "
+ "InitializationError when passed a null Class");
}
}
/**
* Builds the {@link Request} based on provided data.
*
* @throws java.lang.IllegalArgumentException if provided set of data is not valid
*/
public Request build() {
includedPackages.removeAll(excludedPackages);
includedClasses.removeAll(excludedClasses);
validate(includedClasses);
boolean scanningPath = includedClasses.isEmpty();
// If scanning then suite methods are not supported.
boolean ignoreSuiteMethods = this.ignoreSuiteMethods || scanningPath;
AndroidRunnerParams runnerParams =
new AndroidRunnerParams(instr, argsBundle, perTestTimeout, ignoreSuiteMethods);
RunnerBuilder runnerBuilder = getRunnerBuilder(runnerParams, scanningPath);
TestLoader loader = TestLoader.testLoader(classLoader, runnerBuilder, scanningPath);
Collection<String> classNames;
if (scanningPath) {
// no class restrictions have been specified. Load all classes.
classNames = getClassNamesFromClassPath();
} else {
classNames = includedClasses;
}
List<Runner> runners = loader.getRunnersFor(classNames, scanningPath);
Suite suite = ExtendedSuite.createSuite(runners);
Request request = Request.runner(suite);
return new LenientFilterRequest(request, filter);
}
@Test
public void builderHandlesJunit4SuitesTests() throws Throwable {
Runner selectedRunner = androidLogOnlyBuilder.runnerForClass(JUnit4TestSuite.class);
assertThat(selectedRunner, notNullValue());
// Although this returns a Suite all the nested Runner implementations will be
// NonExecutingRunner otherwise there will be failures when run.
assertThat(selectedRunner.getClass(), typeCompatibleWith(Suite.class));
runWithRunner(selectedRunner, 2, 0);
}
private boolean hasSuitableRunnner(final Class<?> clazz) {
final RunWith runWith = clazz.getAnnotation(RunWith.class);
if (runWith != null) {
return (runWith.value().equals(Suite.class));
}
return false;
}
/**
* Verifies that we did not forgot to declare some test classes in the given suite.
* This method scans the directory for {@code *Test.class} files.
*
* <p>This check is disabled if {@link #skipCheckForMissingTests} is {@code true}.</p>
*
* @param suite the suite for which to check for missing tests.
*/
protected static void assertNoMissingTest(final Class<? extends TestSuite> suite) {
if (skipCheckForMissingTests) return;
/*
* Verifies if we are in the Maven target directory. In some IDE configuration, all the ".class" files
* are in the same directory, in which case the verification performed by this method become irrelevant.
*/
final ProjectDirectories dir = new ProjectDirectories(suite);
if (!dir.isMavenModule()) {
return;
}
/*
* Now scan all "*Test.class" in the "target/org" directory and and sub-directories,
* and fail on the first missing test file if any.
*/
List<Class<?>> declared = Arrays.asList(suite.getAnnotation(Suite.SuiteClasses.class).value());
final Set<Class<?>> tests = new HashSet<>(declared);
if (tests.size() != declared.size()) {
declared = new ArrayList<>(declared);
assertTrue(declared.removeAll(tests));
fail("Classes defined twice in " + suite.getSimpleName() + ": " + declared);
}
/*
* Ignore classes that are not really test, like "APIVerifier".
*/
for (final Iterator<Class<?>> it=tests.iterator(); it.hasNext();) {
if (!it.next().getName().endsWith(CLASSNAME_SUFFIX)) {
it.remove();
}
}
final ClassLoader loader = suite.getClassLoader();
final File root = dir.classesRootDirectory.resolve("org").toFile();
removeExistingTests(loader, root, new StringBuilder(120).append(root.getName()), tests);
if (!tests.isEmpty()) {
fail("Classes not found. Are they defined in an other module? " + tests);
}
}
private boolean isJUnit4Suite(TypeElement typeElement) {
return TestingPredicates.hasAnnotation(Suite.SuiteClasses.class).apply(typeElement);
}
private static boolean isSuiteClass(Class<?> cls) {
if (cls.getSuperclass().equals(TestSuite.class)) {
return true;
}
return cls.getAnnotation(Suite.SuiteClasses.class) != null;
}
/**
* Determines if the given {@link Description} is describing a {@link Suite}.
*
* @param description
* the {@link Description} to check, must not be {@code null}
* @return whether the description is describing a Suite
*/
public static boolean isSuite(final Description description) {
final RunWith runWithAnnotation = description.getAnnotation(RunWith.class);
return runWithAnnotation != null && Suite.class.isAssignableFrom(runWithAnnotation.value());
}