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

项目:junit-easy-tools    文件:PotentialAssignmentsTest.java   
@Test
public void shouldFindPossibleAssignmentsFromMethod() throws Throwable {
    this.assignments = new PotentialAssignments(new TestClass(AssignmentsFromMethod.class));
    final List<Assignment> assignments = this.assignments.allPossible().collect(Collectors.toList());

    assertThat(assignments).hasSize(2);

    ArrayList<ParameterSignature> parameterSignature =
            ParameterSignature.signatures(AssignmentsFromMethod.class.getMethod("a", String.class));

    assertThat(assignments.get(0).isValidFor(parameterSignature.get(0)));
    assertThat(assignments.get(0).parameterProducer().produceParamValue()).isEqualTo("42");

    assertThat(assignments.get(1).isValidFor(parameterSignature.get(0)));
    assertThat(assignments.get(1).parameterProducer().produceParamValue()).isEqualTo("27");
}
项目:spockito    文件:Spockito.java   
private static List<Runner> createRunners(final Class<?> clazz) throws InitializationError {
    final ValueConverter defaultValueConverter = getDefaultValueConverter(clazz);
    final List<Runner> runners = new ArrayList<>();
    final Table classWideTable = classWideTableOrNull(clazz);
    if (classWideTable != null) {
        for (final TableRow row : classWideTable) {
            runners.add(new SingleRowMultiTestRunner(clazz, row, defaultValueConverter));
        }
    } else {
        for (final FrameworkMethod testMethod : new TestClass(clazz).getAnnotatedMethods(Test.class)) {
            final Spockito.UseValueConverter useValueConverter = testMethod.getAnnotation(Spockito.UseValueConverter.class);
            final ValueConverter methodValueConverter = Spockito.getValueConverter(useValueConverter, defaultValueConverter);
            runners.add(new SingleTestMultiRowRunner(clazz, testMethod, methodValueConverter));
        }
    }
    return runners;
}
项目:Bytecoder    文件:BytecoderUnitTestRunner.java   
public BytecoderUnitTestRunner(Class aClass) throws InitializationError {
    super(aClass);
    testClass = new TestClass(aClass);
    testMethods = new ArrayList<>();

    Method[] classMethods = aClass.getDeclaredMethods();
    for (Method classMethod : classMethods) {
        Class retClass = classMethod.getReturnType();
        int length = classMethod.getParameterTypes().length;
        int modifiers = classMethod.getModifiers();
        if (retClass == null || length != 0 || Modifier.isStatic(modifiers)
                || !Modifier.isPublic(modifiers) || Modifier.isInterface(modifiers)
                || Modifier.isAbstract(modifiers)) {
            continue;
        }
        String methodName = classMethod.getName();
        if (methodName.toUpperCase().startsWith("TEST")
                || classMethod.getAnnotation(Test.class) != null) {
            testMethods.add(new FrameworkMethod(classMethod));
        }
        if (classMethod.getAnnotation(Ignore.class) != null) {
            testMethods.remove(classMethod);
        }
    }
}
项目:DependencyInjector    文件:MockDependencyHandlerTest.java   
@Test
public void shouldProvideMock() throws Exception {
    // given
    DelayedInjectionRunnerIntegrationTest runnerTest = new DelayedInjectionRunnerIntegrationTest();
    MockitoAnnotations.initMocks(runnerTest);
    TestClass testClass = new TestClass(runnerTest.getClass());
    MockDependencyHandler mockDependencyHandler = new MockDependencyHandler(testClass, runnerTest);
    AlphaService alphaService = mock(AlphaService.class);
    given(injector.getIfAvailable(AlphaService.class)).willReturn(alphaService);

    // when
    Resolution<?> value = mockDependencyHandler.resolve(newContext(AlphaService.class));

    // then
    assertThat(unwrapFromSimpleResolution(value) == alphaService, equalTo(true));
    verify(injector).register(eq(AlphaService.class), any(AlphaService.class));
    verify(injector).register(eq(ClassWithAbstractDependency.AbstractDependency.class),
        any(ClassWithAbstractDependency.AbstractDependency.class));
    verify(injector).getIfAvailable(AlphaService.class);
}
项目:DependencyInjector    文件:MockDependencyHandlerTest.java   
@Test
public void shouldThrowForUnavailableMock() {
    // given
    DelayedInjectionRunnerIntegrationTest runnerTest = new DelayedInjectionRunnerIntegrationTest();
    MockitoAnnotations.initMocks(runnerTest);
    TestClass testClass = new TestClass(runnerTest.getClass());
    MockDependencyHandler mockDependencyHandler = new MockDependencyHandler(testClass, runnerTest);
    given(injector.getIfAvailable(AlphaService.class)).willReturn(null);

    // when
    try {
        mockDependencyHandler.resolve(newContext(AlphaService.class));
        fail("Expected exception to be thrown");
    } catch (InjectorException e) {
        assertThat(e.getMessage(), containsString("dependencies of @InjectDelayed must be provided as @Mock"));
        verify(injector, times(3)).register(any(Class.class), any(Object.class));
        verify(injector).getIfAvailable(AlphaService.class);
    }
}
项目:DependencyInjector    文件:RunDelayedInjectsTest.java   
@Test
public void shouldInitializeInjectDelayedField() throws Throwable {
    // given - test class with initialized @Mock fields
    DelayedInjectionRunnerIntegrationTest runnerTest = new DelayedInjectionRunnerIntegrationTest();
    MockitoAnnotations.initMocks(runnerTest);

    TestClass testClass = new TestClass(runnerTest.getClass());
    Statement nextStatement = mock(Statement.class);
    List<FrameworkField> injectDelayedFields = testClass.getAnnotatedFields(InjectDelayed.class);
    assertThat(injectDelayedFields, hasSize(1)); // assumption
    RunDelayedInjects runDelayedInjects =
        new RunDelayedInjects(nextStatement, testClass, runnerTest, injectDelayedFields);

    // when
    runDelayedInjects.evaluate();

    // then
    assertThat(ReflectionUtils.getFieldValue(injectDelayedFields.get(0).getField(), runnerTest), not(nullValue()));
    verify(nextStatement).evaluate();
}
项目:DependencyInjector    文件:RunDelayedInjectsTest.java   
@Test
public void shouldThrowForAlreadyInitializedField() throws Throwable {
    // given - test class with initialized @Mock fields
    DelayedInjectionRunnerIntegrationTest runnerTest = new DelayedInjectionRunnerIntegrationTest();
    MockitoAnnotations.initMocks(runnerTest);

    TestClass testClass = new TestClass(runnerTest.getClass());
    Statement nextStatement = mock(Statement.class);
    List<FrameworkField> injectDelayedFields = testClass.getAnnotatedFields(InjectDelayed.class);
    assertThat(injectDelayedFields, hasSize(1)); // assumption
    ReflectionUtils.setField(injectDelayedFields.get(0).getField(), runnerTest, mock(SampleInjectClass.class));
    RunDelayedInjects runDelayedInjects =
            new RunDelayedInjects(nextStatement, testClass, runnerTest, injectDelayedFields);

    // when
    try {
        runDelayedInjects.evaluate();
        fail("Expected exception to be thrown");
    } catch (Exception e) {
        assertThat(e.getMessage(), containsString("Field with @InjectDelayed must be null"));
    }
}
项目:DependencyInjector    文件:DelayedInjectionRunnerValidatorTest.java   
@Test
public void shouldValidateUnsuccessfullyForInjectMocksPresence() throws Exception {
    // given
    RunNotifier notifier = mock(RunNotifier.class);
    TestClass testClass = new TestClass(getClass());
    DelayedInjectionRunnerValidator validator = new DelayedInjectionRunnerValidator(notifier, testClass);
    Description description = mock(Description.class);

    // when
    validator.testFinished(description);

    // then
    ArgumentCaptor<Failure> captor = ArgumentCaptor.forClass(Failure.class);
    verify(notifier).fireTestFailure(captor.capture());
    Failure failure = captor.getValue();
    assertThat(failure.getMessage(), containsString("Do not use @InjectMocks"));
}
项目: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()]);
}
项目:parameterized-suite    文件:BlockJUnit4ClassRunnerWithParametersUtil.java   
/**
 * @see BlockJUnit4ClassRunnerWithParameters#createTestUsingFieldInjection()
 */
private static Object createTestUsingFieldInjection(TestClass testClass, Object[] parameters) throws Exception {
    List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter(testClass);
    if (annotatedFieldsByParameter.size() != parameters.length) {
        throw new Exception("Wrong number of parameters and @Parameter fields." + " @Parameter fields counted: " + annotatedFieldsByParameter.size()
                + ", available parameters: " + parameters.length + ".");
    }
    Object testClassInstance = testClass.getJavaClass().newInstance();
    for (FrameworkField each : annotatedFieldsByParameter) {
        Field field = each.getField();
        Parameterized.Parameter annotation = field.getAnnotation(Parameterized.Parameter.class);
        int index = annotation.value();
        try {
            field.set(testClassInstance, parameters[index]);
        } catch (IllegalArgumentException iare) {
            throw new Exception(
                    testClass.getName() + ": Trying to set " + field.getName() + " with the value " + parameters[index] + " that is not the right type ("
                            + parameters[index].getClass().getSimpleName() + " instead of " + field.getType().getSimpleName() + ").",
                    iare);
        }
    }
    return testClassInstance;
}
项目:parameterized-suite    文件:BlockJUnit4ClassRunnerWithParametersUtil.java   
/**
 * Extends a given {@link Statement} for a {@link TestClass} with the evaluation of
 * {@link TestRule}, {@link ClassRule}, {@link Before} and {@link After}.
 * <p>
 * Therefore the test class will be instantiated and parameters will be injected with the same
 * mechanism as in {@link Parameterized}.
 * 
 * Implementation has been extracted from BlockJUnit4ClassRunner#methodBlock(FrameworkMethod).
 * 
 * @param baseStatementWithChildren - A {@link Statement} that includes execution of the test's
 *        children
 * @param testClass - The {@link TestClass} of the test.
 * @param description - The {@link Description} will be passed to the {@link Rule}s and
 *        {@link ClassRule}s.
 * @param singleParameter - The parameters will be injected in attributes annotated with
 *        {@link Parameterized.Parameter} or passed to the constructor otherwise.
 * 
 * @see BlockJUnit4ClassRunnerWithParameters#createTest()
 * @see BlockJUnit4ClassRunner#methodBlock(FrameworkMethod)
 */
public static Statement buildStatementWithTestRules(Statement baseStatementWithChildren, final TestClass testClass, Description description,
        final Object[] singleParameter) {
    final Object test;
    try {
        test = new ReflectiveCallable() {
            protected Object runReflectiveCall() throws Throwable {
                return createInstanceOfParameterizedTest(testClass, singleParameter);
            }
        }.run();
    } catch (Throwable e) {
        return new Fail(e);
    }

    List<TestRule> testRules = BlockJUnit4ClassRunnerUtil.getTestRules(test, testClass);
    Statement statement = BlockJUnit4ClassRunnerUtil.withTestRules(testRules, description, baseStatementWithChildren);

    statement = ParentRunnerUtil.withBeforeClasses(statement, testClass);
    statement = ParentRunnerUtil.withAfterClasses(statement, testClass);
    statement = ParentRunnerUtil.withClassRules(statement, testClass, description);
    return statement;
}
项目: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.newInstance();
                injectorProviderClassCache.put(klass, injectorProvider);
            } catch (Exception e) {
                throwUncheckedException(e);
            }
        }
        return injectorProvider;
    }
    return null;
}
项目:kc-rice    文件:LoadTimeWeavableTestRunner.java   
protected boolean runBootstrapTest(RunNotifier notifier, TestClass testClass) {
    if (!runningBootstrapTest.get().booleanValue()) {
        runningBootstrapTest.set(Boolean.TRUE);
        try {
            BootstrapTest bootstrapTest = getBootstrapTestAnnotation(testClass.getJavaClass());
            if (bootstrapTest != null) {
                Result result = JUnitCore.runClasses(bootstrapTest.value());
                List<Failure> failures = result.getFailures();
                for (Failure failure : failures) {
                    notifier.fireTestFailure(failure);
                }
                return result.getFailureCount() == 0;
            } else {
                throw new IllegalStateException("LoadTimeWeavableTestRunner, must be coupled with an @BootstrapTest annotation to define the bootstrap test to execute.");
            }
        } finally {
            runningBootstrapTest.set(Boolean.FALSE);
        }
    }
    return true;
}
项目: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;
}
项目:pom-manipulation-ext    文件:PlexusTestRunner.java   
@Override
protected Object createTest()
    throws Exception
{
    final TestClass testClass = getTestClass();

    final DefaultContainerConfiguration config = new DefaultContainerConfiguration();

    config.setAutoWiring( true );
    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( Arrays.<PlexusBeanModule> asList( new PlexusAnnotatedBeanModule(
                                                                                                  cs,
                                                                                                  Collections.emptyMap() ) ) );

    return container.lookup( testClass.getJavaClass() );
}
项目:buck-cutom    文件: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;
}
项目: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);
}
项目:emfstore-rest    文件:FuzzyUtil.java   
/**
 * Searches in the resource for a {@link TestConfig} fitting to the given {@link TestClass}.
 * 
 * @param resource
 *            The resource where to search in.
 * @param testClass
 *            The TestClass to which the {@link TestConfig} should fit.
 * @return The {@link TestConfig} fitting to the {@link TestClass}.
 */
public static TestConfig getTestConfig(Resource resource,
    TestClass testClass) {
    // TODO add a standard TestConfig? e.g. where clazz = null / or
    // testconfig for complete packages
    for (EObject object : resource.getContents()) {
        if (object instanceof TestConfig) {
            TestConfig config = (TestConfig) object;
            Class<?> clazz = config.getTestClass();
            if (clazz.getName().equals(testClass.getJavaClass().getName())) {
                return config;
            }
        }
    }

    throw new IllegalArgumentException("No fitting testconfig for "
        + testClass.getName() + " in " + resource.getURI() + " found.");
}
项目: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);
        }
    }
项目:junit-easy-tools    文件:ProducerAssignmentsMultipleParametersTest.java   
@Test
public void shouldAssignNamedProducer() throws Throwable {
    TestClass testClass = new TestClass(ClassWithNamedProducer.class);
    assignments = ProducerAssignments.allUnassigned(
            testClass, testClass.getJavaClass().getMethod("a", String.class));

    List<ParameterProducer> stringParameterProducer = assignments.potentialNextParameterProducers();
    assertThat(stringParameterProducer).hasSize(1);
    assertThat(stringParameterProducer.get(0).produceParamValue()).isEqualTo("27");

    assertThat(assignments.assignNext(stringParameterProducer.get(0)).isComplete()).isTrue();
}
项目:junit-easy-tools    文件:ProducerAssignmentsMethodAsProducerTest.java   
@Test
public void shouldSupportMethodDataProducer() throws Throwable {
    TestClass testClass = new TestClass(ClassWithMethodProducer.class);
    ProducerAssignments assignments = ProducerAssignments.allUnassigned(
            testClass, testClass.getJavaClass().getMethod("a", String.class));

    List<ParameterProducer> parameterProducers = assignments.potentialNextParameterProducers();
    assertThat(parameterProducers).hasSize(1);
    assertThat(parameterProducers.get(0).produceParamValue()).isEqualTo("return");
}
项目:junit-easy-tools    文件:ProducerAssignmentsMethodAsProducerTest.java   
@Test
public void shouldValidateMethodProducerReturnType() throws Exception {
    TestClass testClass = new TestClass(ProducerIsNotCollection.class);
    ProducerAssignments assignments = ProducerAssignments.allUnassigned(
            testClass, testClass.getJavaClass().getMethod("a", String.class));

    assertThatExceptionOfType(InitializationError.class)
            .isThrownBy(assignments::potentialNextParameterProducers);
}
项目:junit-easy-tools    文件:PotentialAssignmentsTest.java   
@Test
public void shouldHaveAssignmentsFromField() throws Throwable {
    this.assignments = new PotentialAssignments(new TestClass(AssignmentsFromField.class));
    List<Assignment> assignments = this.assignments.allPossible().collect(Collectors.toList());
    assertThat(assignments).hasSize(1);

    ArrayList<ParameterSignature> parameterSignature =
            ParameterSignature.signatures(AssignmentsFromField.class.getMethod("a", String.class));

    Assignment assignment = assignments.get(0);
    assertThat(assignment.isValidFor(parameterSignature.get(0))).isTrue();
}
项目:junit-easy-tools    文件:PotentialAssignmentsTest.java   
@Test
public void shouldNotBeValidIfTypeDoesNotMatch() throws Throwable {
    this.assignments = new PotentialAssignments(new TestClass(AssignmentsFromField.class));
    List<Assignment> assignments = this.assignments.allPossible().collect(Collectors.toList());;

    ArrayList<ParameterSignature> parameterSignature =
            ParameterSignature.signatures(AssignmentsFromField.class.getMethod("b", Integer.TYPE));
    Assignment assignment = assignments.get(0);
    assertThat(assignment.isValidFor(parameterSignature.get(0))).isFalse();
}
项目:junit-easy-tools    文件:PotentialAssignmentsTest.java   
@Test
public void shouldProduceValueFromProducer() throws Throwable {
    this.assignments = new PotentialAssignments(new TestClass(AssignmentsFromField.class));
    List<Assignment> assignments = this.assignments.allPossible().collect(Collectors.toList());

    Assignment assignment = assignments.get(0);
    assertThat(assignment.parameterProducer().produceParamValue()).isEqualTo("value");
}
项目:junit-easy-tools    文件:TestObjectTest.java   
@Test
public void shouldCreateObjectUsingFactoryMethod() throws Exception {
    TestClass testClass = new TestClass(ClassWithFactoryMethod.class);
    TestObject testObject = new TestObject(testClass);
    Object result = testObject.createTestObject();
    assertThat(result).isInstanceOf(ClassWithFactoryMethod.class);
    assertThat(((ClassWithFactoryMethod)result).injected).isEqualTo("injected");
}
项目:junit-easy-tools    文件:ProducerStatementTest.java   
@Test
public void shouldThrowExceptionIfAllTheAssumptionsFails() throws Throwable {
    TestClass testClass = new TestClass(ExceptionOnNoAssumption.class);
    FrameworkMethod method =
            new FrameworkMethod(ExceptionOnNoAssumption.class.getMethod("a", Integer.class));
    ProducerStatement producerStatement = new ProducerStatement(testClass, method);

    assertThatExceptionOfType(AssertionError.class)
            .isThrownBy(producerStatement::evaluate);
}
项目:junit-easy-tools    文件:ProducerStatementTest.java   
@Test
public void shouldNotThrowExceptionIfAtLeastOneAssumptionPass() throws Throwable {
    TestClass testClass = new TestClass(ExceptionOnNoAssumption.class);
    FrameworkMethod method =
            new FrameworkMethod(ExceptionOnNoAssumption.class.getMethod("b", Integer.class));
    ProducerStatement producerStatement = new ProducerStatement(testClass, method);

    producerStatement.evaluate();
}
项目:DependencyInjector    文件:DelayedInjectionRunnerValidatorTest.java   
@Test
public void shouldValidateSuccessfully() throws Exception {
    // given
    RunNotifier notifier = mock(RunNotifier.class);
    TestClass testClass = new TestClass(DelayedInjectionRunnerIntegrationTest.class);
    DelayedInjectionRunnerValidator validator = new DelayedInjectionRunnerValidator(notifier, testClass);
    Description description = mock(Description.class);

    // when
    validator.testFinished(description);

    // then
    // nothing happens: successful validation
    verifyZeroInteractions(notifier, description);
}
项目:Minerva    文件:ParameterizedRobolectricGradleTestRunner.java   
private FrameworkMethod getParametersMethod() throws Exception {
    TestClass testClass = getTestClass();
    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());
}
项目:unitils    文件:UnitilsParameterized.java   
/**
 * @param javaClass
 * @param parametersList
 * @param i
 * @throws Exception 
 */
public TestClassRunnerForParameters(Class<?> javaClass, List<Object[]> parametersList, int i) throws Exception {
    super(javaClass);
    this.fParameterList = parametersList;
    this.fParameterSetNumber = i;
    this.testClassInternalRunners = new org.junit.internal.runners.TestClass(javaClass);
}
项目:unitils    文件:UnitilsParameterized.java   
/**
 * @see org.junit.internal.runners.JUnit4ClassRunner#validate()
 */
@Override
protected void validate() throws InitializationError {
    testClassInternalRunners = new org.junit.internal.runners.TestClass(clazz);
    UnitilsMethodValidator validator = new UnitilsMethodValidator(testClassInternalRunners);
    List<Throwable> errors = validator.validateMethodsForParameterizedRunner();
    if (!errors.isEmpty()) {
        throw new InitializationError(errors);
    }
}
项目:unitils    文件:UnitilsParameterized.java   
/**
 * @param testClass
 * @return
 */
protected 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());
}
项目:unitils    文件:UnitilsParameterized.java   
public void validateArgConstructor() {
    org.junit.runners.model.TestClass clazz = new org.junit.runners.model.TestClass(testclass.getJavaClass());
    Constructor<?> onlyConstructor = clazz.getOnlyConstructor();

    if (onlyConstructor.getParameterTypes().length == 0) {
        errors.add(new Exception("Test class shouldn't have a public zero-argument constructor"));
    }

}
项目:aspectj-junit-runner    文件:AspectJUnit4Runner.java   
protected TestClass createTestClass(Class<?> clazz) {
    URL[] classpath = computeClasspath(clazz);
    cl = new WeavingURLClassLoader(classpath, null);
    clazz = loadClassFromClassLoader(clazz, cl);
    testClass = new TestClass(clazz);
    return testClass;
}
项目:parameterized-suite    文件:ParameterizedUtil.java   
/**
 * @param testClass
 * @return the parameters from the method annotated with {@link Parameters}
 * @throws Throwable
 * 
 * @see Parameterized#allParameters()
 */
@SuppressWarnings("unchecked")
public static Iterable<Object> getParameters(TestClass testClass) throws Throwable {
    Object parameters = getParametersMethod(testClass).invokeExplosively(null);
    if (parameters instanceof Iterable) {
        return (Iterable<Object>) parameters;
    } else if (parameters instanceof Object[]) {
        return Arrays.asList((Object[]) parameters);
    } else {
        throw parametersMethodReturnedWrongType(testClass);
    }
}
项目:parameterized-suite    文件:ParameterizedUtil.java   
/**
 * @param testClass
 * @return the method annotated with {@link Parameters}
 * @throws Exception
 * 
 * @see Parameterized#allParameters()
 */
private static FrameworkMethod getParametersMethod(TestClass testClass) throws Exception {
    List<FrameworkMethod> methods = testClass.getAnnotatedMethods(Parameters.class);
    for (FrameworkMethod each : methods) {
        if (each.isStatic() && each.isPublic()) {
            return each;
        }
    }

    throw new Exception("No public static parameters method on class " + testClass.getName());
}
项目:parameterized-suite    文件:ParameterizedUtil.java   
/**
 * @see Parameterized#parametersMethodReturnedWrongType()
 */
private static Exception parametersMethodReturnedWrongType(TestClass testClass) throws Exception {
    String className = testClass.getName();
    String methodName = getParametersMethod(testClass).getName();
    String message = MessageFormat.format("{0}.{1}() must return an Iterable of arrays.", className, methodName);
    return new Exception(message);
}
项目:parameterized-suite    文件:BlockJUnit4ClassRunnerWithParametersUtil.java   
/**
 * @see BlockJUnit4ClassRunnerWithParameters#createTest()
 */
public static Object createInstanceOfParameterizedTest(TestClass testClass, Object[] parameters) throws Exception {
    InjectionType injectionType = getInjectionType(testClass);
    switch (injectionType) {
        case CONSTRUCTOR:
            return createTestUsingConstructorInjection(testClass, parameters);
        case FIELD:
            return createTestUsingFieldInjection(testClass, parameters);
        default:
            throw new IllegalStateException("The injection type " + injectionType + " is not supported.");
    }
}
项目:parameterized-suite    文件:BlockJUnit4ClassRunnerWithParametersUtil.java   
/**
 * @see BlockJUnit4ClassRunnerWithParameters#getInjectionType()
 */
private static InjectionType getInjectionType(TestClass testClass) {
    if (fieldsAreAnnotated(testClass)) {
        return InjectionType.FIELD;
    } else {
        return InjectionType.CONSTRUCTOR;
    }
}