org.junit.runners.model.TestClass Java Examples

The following examples show how to use org.junit.runners.model.TestClass. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NamedParameterizedRunner.java    From sql-layer with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #2
Source File: BaseRunner.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
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()]);
}
 
Example #3
Source File: PlexusTestRunner.java    From pom-manipulation-ext with Apache License 2.0 6 votes vote down vote up
@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() );
}
 
Example #4
Source File: BytecoderUnitTestRunner.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
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));
        }
    }
}
 
Example #5
Source File: ExternalTests.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #6
Source File: Injected.java    From ion-java with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #7
Source File: BurstJUnit4.java    From burst with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #8
Source File: DataProviderResolverAcceptanceTest.java    From junit-dataprovider with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #9
Source File: WildflyTestRunner.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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);
        }
    }
 
Example #10
Source File: WildflyTestRunner.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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;
}
 
Example #11
Source File: BuckBlockJUnit4ClassRunner.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example #12
Source File: AgentRunner.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
/**
 * 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()));
      }
    }
  };
}
 
Example #13
Source File: DefaultDataProviderMethodResolverTest.java    From junit-dataprovider with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #14
Source File: InjectorProviders.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
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;
}
 
Example #15
Source File: InjectorProviders.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
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;
}
 
Example #16
Source File: WildflyTestRunner.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void prepareSetupTasks(TestClass klass) {
    try {
        if (klass.getJavaClass().isAnnotationPresent(ServerSetup.class)) {
            ServerSetup serverSetup = klass.getAnnotation(ServerSetup.class);
            for (Class<? extends ServerSetupTask> clazz : serverSetup.value()) {
                Constructor<? extends ServerSetupTask> ctor = clazz.getDeclaredConstructor();
                ctor.setAccessible(true);
                serverSetupTasks.add(ctor.newInstance());
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #17
Source File: CdiTestRunner.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
private Statement wrapAfterStatement(Statement statement, TestClass testClass, Object target)
{
    for (TestStatementDecoratorFactory statementHandler : this.statementDecoratorFactories)
    {
        Statement result = statementHandler.createAfterStatement(statement, testClass, target);
        if (result != null)
        {
            statement = result;
        }
    }
    return statement;
}
 
Example #18
Source File: TestClassStatement.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #19
Source File: ParameterizedRunner.java    From es6draft with MIT License 5 votes vote down vote up
@Override
protected TestClass createTestClass(Class<?> clazz) {
    TestClass testClass = testClasses.get(clazz);
    if (testClass == null) {
        testClasses.put(clazz, testClass = new TestClass(clazz));
    }
    return testClass;
}
 
Example #20
Source File: LoadTimeWeavableTestRunner.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Returns a {@link org.junit.runners.model.TestClass} object wrapping the class to be executed.
 */
public final TestClass getTestClass() {
    if (fTestClass == null) {
        throw new IllegalStateException("Attempted to access test class but it has not yet been initialized!");
    }
    return fTestClass;
}
 
Example #21
Source File: WildflyTestRunner.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private FrameworkField findParameterField(final TestClass testClass) {
    final List<FrameworkField> fields = testClass.getAnnotatedFields(Parameter.class);
    if (fields.size() > 1) {
        throw new RuntimeException(String.format("More than one field was annotated with @%s: %s",
                Parameter.class.getSimpleName(), fields));
    } else if (fields.isEmpty()) {
        throw new RuntimeException(String.format("If the @%s annotation is present on a method a field must be annotated with @%s",
                Parameters.class.getSimpleName(), Parameter.class.getSimpleName()));
    }
    return fields.get(0);
}
 
Example #22
Source File: WildflyTestRunner.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Collection<Object> resolveParameters(final TestClass testClass) {
    final FrameworkMethod method = findParametersMethod(testClass);
    if (method == null) {
        return Collections.emptyList();
    }
    try {
        return (Collection<Object>) method.invokeExplosively(null);
    } catch (Throwable t) {
        throw new RuntimeException(String.format("Failed to invoke method %s on test %s", method.getName(), testClass.getName()), t);
    }
}
 
Example #23
Source File: WildflyTestRunner.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private FrameworkMethod findParametersMethod(final TestClass testClass) {
    final List<FrameworkMethod> methods = testClass.getAnnotatedMethods(Parameters.class);
    if (methods.size() > 1) {
        throw new RuntimeException(String.format("More than one method was annotated with @%s: %s",
                Parameters.class.getSimpleName(), methods));
    } else if (methods.isEmpty()) {
        return null;
    }
    final FrameworkMethod method = methods.get(0);
    if (method.isPublic() && method.isStatic() && Collection.class.isAssignableFrom(method.getReturnType())) {
        return method;
    }
    throw new RuntimeException(String.format("Method %s must be public, static and have a return type assignable to Collection<Object>.",
            method.getName()));
}
 
Example #24
Source File: TestContext.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
public TestClass createTestClass(Class<?> testClass) {
    try {
        final Class<?> testClazz = classLoader.loadClass(testClass.getName());
        return new TestClass(testClazz);
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
 
Example #25
Source File: RandomizedRepeatRunner.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
private static int getNumTimes(TestClass klass) {
	Annotation[] anns = klass.getAnnotations();
	for (int i = 0; i < anns.length; i++) {
		if (anns[i] instanceof RandomizedRepeat) {
			return ((RandomizedRepeat) anns[i]).value();
		}
	}
	return 1;
}
 
Example #26
Source File: RuleContext.java    From spectrum with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
RuleContext(final T object) {
  this.ruleClass = (Class<T>) object.getClass();
  this.testClass = new TestClass(this.ruleClass);
  this.currentTestObject = object;
  this.constructEveryTime = false;
}
 
Example #27
Source File: ParameterizedMultiRunner.java    From cougar with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #28
Source File: PolySuite.java    From elk-reasoner with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #29
Source File: Injected.java    From ion-java with Apache License 2.0 5 votes vote down vote up
private static Dimension[] findDimensions(TestClass testClass)
throws Throwable
{
    List<FrameworkField> fields =
        testClass.getAnnotatedFields(Inject.class);
    if (fields.isEmpty())
    {
        throw new Exception("No fields of " + testClass.getName()
                            + " have the @Inject annotation");
    }

    BeanInfo beanInfo = Introspector.getBeanInfo(testClass.getJavaClass());
    PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();

    Dimension[] dimensions = new Dimension[fields.size()];

    int i = 0;
    for (FrameworkField field : fields)
    {
        int modifiers = field.getField().getModifiers();
        if (! Modifier.isPublic(modifiers) || ! Modifier.isStatic(modifiers))
        {
            throw new Exception("@Inject " + testClass.getName() + '.'
                                + field.getField().getName()
                                + " must be public static");
        }

        Dimension dim = new Dimension();
        dim.property = field.getField().getAnnotation(Inject.class).value();
        dim.descriptor = findDescriptor(testClass, descriptors, field, dim.property);
        dim.values = (Object[]) field.get(null);
        dimensions[i++] = dim;
    }

    return dimensions;
}
 
Example #30
Source File: SharedBehaviorTesting.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
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");
}