下面列出了怎么用org.junit.runners.model.TestClass的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Creates the {@link TestClass} object for this JUnit runner with the
* specified test class.
* <p>
* This method has been overridden to retrofit the {@link FrameworkMethod}
* objects.
*
* @param testClass The test class.
* @return The {@link TestClass} object for this JUnit runner with the
* specified test class.
*/
@Override
protected TestClass createTestClass(final Class<?> testClass) {
return new TestClass(testClass) {
@Override
public List<FrameworkMethod> getAnnotatedMethods(final Class<? extends Annotation> annotationClass) {
final List<FrameworkMethod> retrofitted = new ArrayList<>();
for (final FrameworkMethod method : super.getAnnotatedMethods(annotationClass))
retrofitted.add(retrofitMethod(method));
return Collections.unmodifiableList(retrofitted);
}
@Override
protected void scanAnnotatedMembers(final Map<Class<? extends Annotation>,List<FrameworkMethod>> methodsForAnnotations, final Map<Class<? extends Annotation>,List<FrameworkField>> fieldsForAnnotations) {
super.scanAnnotatedMembers(methodsForAnnotations, fieldsForAnnotations);
for (final Map.Entry<Class<? extends Annotation>,List<FrameworkMethod>> entry : methodsForAnnotations.entrySet()) {
final ListIterator<FrameworkMethod> iterator = entry.getValue().listIterator();
while (iterator.hasNext())
iterator.set(retrofitMethod(iterator.next()));
}
}
};
}
/**
* @return {@code true} if the test class has any fields annotated with {@code Rule} whose type is
* {@link Timeout}.
*/
static boolean hasTimeoutRule(TestClass testClass) {
// Many protected convenience methods in BlockJUnit4ClassRunner that are available in JUnit 4.11
// such as getTestRules(Object) were not public until
// https://github.com/junit-team/junit/commit/8782efa08abf5d47afdc16740678661443706740,
// which appears to be JUnit 4.9. Because we allow users to use JUnit 4.7, we need to include a
// custom implementation that is backwards compatible to JUnit 4.7.
List<FrameworkField> fields = testClass.getAnnotatedFields(Rule.class);
for (FrameworkField field : fields) {
if (field.getField().getType().equals(Timeout.class)) {
return true;
}
}
return false;
}
private void testJVMBackendFrameworkMethod(final FrameworkMethod aFrameworkMethod, final RunNotifier aRunNotifier) {
if ("".equals(System.getProperty("BYTECODER_DISABLE_JVMTESTS", ""))) {
final TestClass testClass = getTestClass();
final Description theDescription = Description.createTestDescription(testClass.getJavaClass(), aFrameworkMethod.getName() + " JVM Target");
aRunNotifier.fireTestStarted(theDescription);
try {
// Simply invoke using reflection
final Object theInstance = testClass.getJavaClass().getDeclaredConstructor().newInstance();
final Method theMethod = aFrameworkMethod.getMethod();
theMethod.invoke(theInstance);
aRunNotifier.fireTestFinished(theDescription);
} catch (final Exception e) {
aRunNotifier.fireTestFailure(new Failure(theDescription, e));
}
}
}
protected ServiceTest[] getServices()
{
TestClass test = getTestClass();
ServiceTests config
= test.getAnnotation(ServiceTests.class);
if (config != null)
return config.value();
Annotation[] annotations = test.getAnnotations();
List<ServiceTest> list = new ArrayList<>();
for (Annotation annotation : annotations) {
if (ServiceTest.class.isAssignableFrom(annotation.getClass()))
list.add((ServiceTest) annotation);
}
return list.toArray(new ServiceTest[list.size()]);
}
public static IInjectorProvider getOrCreateInjectorProvider(TestClass testClass) {
InjectWith injectWith = testClass.getJavaClass().getAnnotation(InjectWith.class);
if (injectWith != null) {
Class<? extends IInjectorProvider> klass = injectWith.value();
IInjectorProvider injectorProvider = injectorProviderClassCache.get(klass);
if (injectorProvider == null) {
try {
injectorProvider = klass.getDeclaredConstructor().newInstance();
injectorProviderClassCache.put(klass, injectorProvider);
} catch (Exception e) {
throwUncheckedException(e);
}
}
return injectorProvider;
}
return null;
}
public static IInjectorProvider getOrCreateInjectorProvider(TestClass testClass) {
InjectWith injectWith = testClass.getJavaClass().getAnnotation(InjectWith.class);
if (injectWith != null) {
Class<? extends IInjectorProvider> klass = injectWith.value();
IInjectorProvider injectorProvider = injectorProviderClassCache.get(klass);
if (injectorProvider == null) {
try {
injectorProvider = klass.getDeclaredConstructor().newInstance();
injectorProviderClassCache.put(klass, injectorProvider);
} catch (Exception e) {
throwUncheckedException(e);
}
}
return injectorProvider;
}
return null;
}
/**
* Gets the parameterization
* @return the parameterization collection
* @throws Throwable if the annotation requirements are not met, or if there's an error in invoking
* the class's "get parameterizations" method.
*/
private Collection<Parameterization> getParameterizations() throws Throwable
{
TestClass cls = getTestClass();
List<FrameworkMethod> methods = cls.getAnnotatedMethods(TestParameters.class);
if (methods.size() != 1)
{
throw new Exception("class " + cls.getName() + " must have exactly 1 method annotated with "
+ TestParameters.class.getSimpleName() +"; found " + methods.size());
}
FrameworkMethod method = methods.get(0);
checkParameterizationMethod(method);
@SuppressWarnings("unchecked")
Collection<Parameterization> ret = (Collection<Parameterization>) method.invokeExplosively(null);
checkParameterizations(ret);
return ret;
}
private static PropertyDescriptor findDescriptor(TestClass testClass,
PropertyDescriptor[] descriptors,
FrameworkField field,
String name)
throws Exception
{
for (PropertyDescriptor d : descriptors)
{
if (d.getName().equals(name))
{
if (d.getWriteMethod() == null) break; // To throw error
return d;
}
}
throw new Exception("@Inject value '" + name
+ "' doesn't match a writeable property near "
+ testClass.getName() + '.'
+ field.getField().getName());
}
@SuppressWarnings("unchecked")
private static <T extends Annotation, WT extends Annotation> List<T> groupAnnotations(TestClass testClass, Class<T> annoType, Class<WT> wrapperType) {
try {
List<T> annotations = new ArrayList<>();
WT testsAnn = testClass.getAnnotation(wrapperType);
if (testsAnn != null) {
annotations.addAll(asList((T[]) wrapperType.getMethod("value").invoke(testsAnn)));
}
T singularAnn = testClass.getAnnotation(annoType);
if (singularAnn != null) {
annotations.add(singularAnn);
}
return annotations;
} catch (ReflectiveOperationException e) {
throw new IllegalArgumentException(e);
}
}
static List<Runner> explode(Class<?> cls) throws InitializationError {
checkNotNull(cls, "cls");
TestClass testClass = new TestClass(cls);
List<FrameworkMethod> testMethods = testClass.getAnnotatedMethods(Test.class);
List<FrameworkMethod> burstMethods = new ArrayList<>(testMethods.size());
for (FrameworkMethod testMethod : testMethods) {
Method method = testMethod.getMethod();
for (Enum<?>[] methodArgs : Burst.explodeArguments(method)) {
burstMethods.add(new BurstMethod(method, methodArgs));
}
}
TestConstructor constructor = BurstableConstructor.findSingle(cls);
Enum<?>[][] constructorArgsList = Burst.explodeArguments(constructor);
List<Runner> burstRunners = new ArrayList<>(constructorArgsList.length);
for (Enum<?>[] constructorArgs : constructorArgsList) {
burstRunners.add(new BurstRunner(cls, constructor, constructorArgs, burstMethods));
}
return unmodifiableList(burstRunners);
}
private void doInject(TestClass klass, Object instance) {
try {
for (FrameworkField frameworkField : klass.getAnnotatedFields(Inject.class)) {
Field field = frameworkField.getField();
if ((instance == null && Modifier.isStatic(field.getModifiers()) ||
instance != null)) {//we want to do injection even on static fields before test run, so we make sure that client is correct for current state of server
field.setAccessible(true);
if (field.getType() == ManagementClient.class && controller.isStarted()) {
field.set(instance, controller.getClient());
} else if (field.getType() == ModelControllerClient.class && controller.isStarted()) {
field.set(instance, controller.getClient().getControllerClient());
} else if (field.getType() == ServerController.class) {
field.set(instance, controller);
}
}
}
} catch (Exception e) {
throw new RuntimeException("Failed to inject", e);
}
}
@Override
protected List<FrameworkMethod> getChildren() {
final List<FrameworkMethod> result = new ArrayList<>();
final TestClass testClass = getTestClass();
final Collection<Object> parameters = resolveParameters(testClass);
// If there are no resolved parameters we can just use the default methods
if (parameters.isEmpty()) {
result.addAll(super.getChildren());
} else {
final FrameworkField field = findParameterField(testClass);
for (FrameworkMethod method : super.getChildren()) {
for (Object value : parameters) {
parameterDescriptions.add(method, field, value);
// Add the same method for each parameter value
result.add(method);
}
}
}
return result;
}
@Override
protected Object createTest()
throws Exception
{
final TestClass testClass = getTestClass();
final DefaultContainerConfiguration config = new DefaultContainerConfiguration();
// setAutoWiring is set implicitly by below.
config.setClassPathScanning( PlexusConstants.SCANNING_ON );
config.setComponentVisibility( PlexusConstants.GLOBAL_VISIBILITY );
config.setName( testClass.getName() );
final DefaultPlexusContainer container = new DefaultPlexusContainer( config );
final ClassSpace cs = new URLClassSpace( Thread.currentThread().getContextClassLoader() );
container.addPlexusInjector( Collections.<PlexusBeanModule>singletonList( new PlexusAnnotatedBeanModule( cs, Collections.emptyMap() ) ) );
return container.lookup( testClass.getJavaClass() );
}
@Override
protected List<FrameworkMethod> findDataProviderMethods(List<TestClass> locations, String testMethodName,
String useDataProviderValue) {
List<FrameworkMethod> result = new ArrayList<FrameworkMethod>();
for (TestClass location : locations) {
List<FrameworkMethod> dataProviderMethods = location.getAnnotatedMethods(DataProvider.class);
for (FrameworkMethod dataProviderMethod : dataProviderMethods) {
if (dataProviderMethod.getName().startsWith(testMethodName)) {
result.add(dataProviderMethod);
}
}
}
Collections.sort(result, new Comparator<FrameworkMethod>() {
@Override
public int compare(FrameworkMethod a, FrameworkMethod b) {
return a.getName().compareTo(b.getName());
}
});
return result;
}
@Test
public void testFindDataProviderMethodsShouldReturnNotNullTestClasses() {
// Given:
final List<TestClass> dataProviderLocations = testClassesFor(DataConverterTest.class, TestGeneratorTest.class,
TestValidatorTest.class);
final String testMethodName = "testMethodName";
final String useDataProviderValue = "availableDataProviderMethodName";
FrameworkMethod dataProviderMethod2 = mock(FrameworkMethod.class);
when(underTest.findDataProviderMethod(dataProviderLocations.get(0), testMethodName, useDataProviderValue))
.thenReturn(dataProviderMethod);
when(underTest.findDataProviderMethod(dataProviderLocations.get(1), testMethodName, useDataProviderValue)).thenReturn(null);
when(underTest.findDataProviderMethod(dataProviderLocations.get(2), testMethodName, useDataProviderValue))
.thenReturn(dataProviderMethod2);
// When:
List<FrameworkMethod> result = underTest.findDataProviderMethods(dataProviderLocations, testMethodName, useDataProviderValue);
// Then:
assertThat(result).containsExactly(dataProviderMethod, dataProviderMethod2);
}
private FrameworkMethod getParametersMethod(TestClass testClass) throws Exception {
List<FrameworkMethod> methods = testClass.getAnnotatedMethods(Parameters.class);
for (FrameworkMethod each : methods) {
int modifiers = each.getMethod().getModifiers();
if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))
return each;
}
throw new Exception("No public static parameters method on class " + testClass.getName());
}
private static TestWithParameters createTestWithParameters(
final TestClass testClass, final String pattern, final int index, final Object[] parameters) {
final String finalPattern = pattern.replaceAll("\\{index\\}",
Integer.toString(index));
final String name = MessageFormat.format(finalPattern, parameters);
return new TestWithParameters("[" + name + "]", testClass,
Arrays.asList(parameters));
}
@Override
protected TestClass createTestClass(Class<?> testClass) {
try {
if (!DelegateArkContainer.isStarted()) {
DelegateArkContainer.launch(testClass);
}
ClassLoader testClassLoader = DelegateArkContainer.getTestClassLoader();
TestClass testKlazz = super.createTestClass(testClassLoader.loadClass(testClass
.getName()));
ClassLoaderUtils.pushContextClassLoader(ClassLoader.getSystemClassLoader());
return testKlazz;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Override
protected TestClass createTestClass(Class<?> testClass) {
try {
return new TestClass(CompilerTreeApiTestRunner.reloadFromCompilerClassLoader(testClass));
} catch (InitializationError initializationError) {
throw new AssertionError(initializationError);
}
}
public FuzzStatement(FrameworkMethod method, TestClass testClass,
GeneratorRepository generatorRepository) {
this.method = method;
this.testClass = testClass;
this.typeVariables =
GenericsResolver.resolve(testClass.getJavaClass())
.method(method.getMethod())
.genericsMap();
this.generatorRepository = generatorRepository;
this.expectedExceptions = Arrays.asList(method.getMethod().getExceptionTypes());
}
@Override
protected List<FrameworkMethodWithTestOption> getChildren() {
final List<FrameworkMethodWithTestOption> testMethods = new ArrayList<>();
final TestClass testClass = getTestClass();
final Method[] classMethods = testClass.getJavaClass().getDeclaredMethods();
for (final Method classMethod : classMethods) {
final Class retClass = classMethod.getReturnType();
final int length = classMethod.getParameterTypes().length;
final int modifiers = classMethod.getModifiers();
if (null == retClass || 0 != length || Modifier.isStatic(modifiers)
|| !Modifier.isPublic(modifiers) || Modifier.isInterface(modifiers)
|| Modifier.isAbstract(modifiers)) {
continue;
}
final String methodName = classMethod.getName();
if (methodName.toUpperCase().startsWith("TEST")
|| null != classMethod.getAnnotation(Test.class)) {
if (classMethod.isAnnotationPresent(Ignore.class)) {
testMethods.add(new FrameworkMethodWithTestOption(classMethod, testOptions.get(0)));
} else {
for (final TestOption o : testOptions) {
testMethods.add(new FrameworkMethodWithTestOption(classMethod, o));
}
}
}
}
return testMethods;
}
private Statement wrapBeforeStatement(Statement statement, TestClass testClass, Object target)
{
for (TestStatementDecoratorFactory statementHandler : this.statementDecoratorFactories)
{
Statement result = statementHandler.createBeforeStatement(statement, testClass, target);
if (result != null)
{
statement = result;
}
}
return statement;
}
private TestWithParameters createTestWithParameters(
TestClass testClass, String pattern, int index,
Object[] parameters) {
String finalPattern = pattern.replaceAll("\\{index\\}",
Integer.toString(index));
String name = MessageFormat.format(finalPattern, parameters);
return new TestWithParameters("[" + name + "]", testClass,
Arrays.asList(parameters));
}
public static IInjectorProvider getInjectorProvider(TestClass testClass) {
InjectWith injectWith = testClass.getJavaClass().getAnnotation(InjectWith.class);
if (injectWith != null) {
return injectorProviderClassCache.get(injectWith.value());
}
return null;
}
public static IInjectorProvider createInjectorProvider(TestClass testClass) {
InjectWith injectWith = testClass.getJavaClass().getAnnotation(InjectWith.class);
if (injectWith != null) {
try {
return injectWith.value().getDeclaredConstructor().newInstance();
} catch (Exception e) {
throwUncheckedException(e);
}
}
return null;
}
private void afterAll() throws Exception {
Integer counter = (Integer) ctx.getData(counterKey);
if (counter == null) {
counter = 0;
}
ctx.storeData(counterKey, ++counter);
final List<FrameworkMethod> testMethods = new TestClass(target.getClass()).getAnnotatedMethods(Test.class);
if (counter >= testMethods.size()) {
executor.processAfterAll(this);
}
}
public static IInjectorProvider getInjectorProvider(TestClass testClass) {
InjectWith injectWith = testClass.getJavaClass().getAnnotation(InjectWith.class);
if (injectWith != null) {
return injectorProviderClassCache.get(injectWith.value());
}
return null;
}
public static IInjectorProvider createInjectorProvider(TestClass testClass) {
InjectWith injectWith = testClass.getJavaClass().getAnnotation(InjectWith.class);
if (injectWith != null) {
try {
return injectWith.value().getDeclaredConstructor().newInstance();
} catch (Exception e) {
throwUncheckedException(e);
}
}
return null;
}
private static FrameworkMethod getConfigMethod(TestClass testClass) {
List<FrameworkMethod> methods = testClass.getAnnotatedMethods(Config.class);
if (methods.isEmpty()) {
throw new IllegalStateException("@" + Config.class.getSimpleName() + " method not found");
}
if (methods.size() > 1) {
throw new IllegalStateException("Too many @" + Config.class.getSimpleName() + " methods");
}
FrameworkMethod method = methods.get(0);
int modifiers = method.getMethod().getModifiers();
if (!(Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
throw new IllegalStateException("@" + Config.class.getSimpleName() + " method \"" + method.getName() + "\" must be public static");
}
return method;
}
public SharedBehaviorTesting(
Function<RunNotifier, Statement> superChildrenInvoker,
BiConsumer<FrameworkMethod, RunNotifier> superChildRunner,
TestSupplier superCreateTest,
Supplier<Description> superDescription,
Supplier<TestClass> testClass,
BiFunction<Class<?>, String, Description> descriptionFactory,
FeatureSet features)
throws InitializationError {
this.superChildrenInvoker = superChildrenInvoker;
this.superChildRunner = superChildRunner;
this.superCreateTest = superCreateTest;
this.superDescription = superDescription;
this.features = features;
List<FrameworkField> testerFields = testClass.get().getAnnotatedFields(Shared.class);
if (testerFields.isEmpty()) {
throw new InitializationError("No public @Shared field found");
} else if (testerFields.size() > 1) {
throw new InitializationError("Multiple public @Shared fields found");
}
FrameworkField frameworkField = getOnlyElement(testerFields);
if (!frameworkField.isPublic()) {
throw new InitializationError("@Shared field " + frameworkField + " must be public");
}
if (!frameworkField.getType().isAssignableFrom(BehaviorTester.class)) {
throw new InitializationError(String.format(
"@Shared field %s must be of type %s",
frameworkField,
BehaviorTester.class.getSimpleName()));
}
testerField = frameworkField.getField();
introspection = descriptionFactory.apply(testClass.get().getJavaClass(), "Introspect");
}