类org.junit.runners.model.TestClass源码实例Demo

下面列出了怎么用org.junit.runners.model.TestClass的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: java-specialagent   文件: AgentRunner.java
/**
 * 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()));
      }
    }
  };
}
 
源代码2 项目: buck   文件: BuckBlockJUnit4ClassRunner.java
/**
 * @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;
}
 
源代码3 项目: Bytecoder   文件: BytecoderUnitTestRunner.java
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));
        }
    }
}
 
源代码4 项目: baratine   文件: BaseRunner.java
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()]);
}
 
源代码5 项目: xtext-eclipse   文件: InjectorProviders.java
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;
}
 
源代码6 项目: xtext-core   文件: InjectorProviders.java
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;
}
 
源代码7 项目: sql-layer   文件: NamedParameterizedRunner.java
/**
 * 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;
}
 
源代码8 项目: ion-java   文件: Injected.java
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());
}
 
源代码9 项目: ehcache3   文件: ExternalTests.java
@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);
  }
}
 
源代码10 项目: burst   文件: BurstJUnit4.java
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);
}
 
源代码11 项目: wildfly-core   文件: WildflyTestRunner.java
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);
        }
    }
 
源代码12 项目: wildfly-core   文件: WildflyTestRunner.java
@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;
}
 
源代码13 项目: pom-manipulation-ext   文件: PlexusTestRunner.java
@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);
}
 
源代码16 项目: tds   文件: SpringJUnit4ParameterizedClassRunner.java
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());
}
 
源代码17 项目: htmlunit   文件: BrowserParameterizedRunner.java
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));
}
 
源代码18 项目: sofa-ark   文件: ArkJUnit4Runner.java
@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);
    }
}
 
源代码19 项目: buck   文件: CompilerTreeApiParameterized.java
@Override
protected TestClass createTestClass(Class<?> testClass) {
  try {
    return new TestClass(CompilerTreeApiTestRunner.reloadFromCompilerClassLoader(testClass));
  } catch (InitializationError initializationError) {
    throw new AssertionError(initializationError);
  }
}
 
源代码20 项目: JQF   文件: FuzzStatement.java
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());

}
 
源代码21 项目: Bytecoder   文件: BytecoderUnitTestRunner.java
@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;
}
 
源代码22 项目: deltaspike   文件: CdiTestRunner.java
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;
}
 
源代码23 项目: registry   文件: CustomParameterizedRunner.java
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));
}
 
源代码24 项目: xtext-eclipse   文件: InjectorProviders.java
public static IInjectorProvider getInjectorProvider(TestClass testClass) {
	InjectWith injectWith = testClass.getJavaClass().getAnnotation(InjectWith.class);
	if (injectWith != null) {
		return injectorProviderClassCache.get(injectWith.value());
	}
	return null;
}
 
源代码25 项目: xtext-eclipse   文件: InjectorProviders.java
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;
}
 
源代码26 项目: jpa-unit   文件: TestClassStatement.java
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);
    }
}
 
源代码27 项目: xtext-core   文件: InjectorProviders.java
public static IInjectorProvider getInjectorProvider(TestClass testClass) {
	InjectWith injectWith = testClass.getJavaClass().getAnnotation(InjectWith.class);
	if (injectWith != null) {
		return injectorProviderClassCache.get(injectWith.value());
	}
	return null;
}
 
源代码28 项目: xtext-core   文件: InjectorProviders.java
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;
}
 
源代码29 项目: elk-reasoner   文件: PolySuite.java
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;
}
 
源代码30 项目: FreeBuilder   文件: SharedBehaviorTesting.java
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");
}
 
 类所在包
 同包方法