Java Code Examples for org.junit.runners.model.FrameworkMethod

The following are top voted examples for showing how to use org.junit.runners.model.FrameworkMethod. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: junit-easy-tools   File: PotentialAssignments.java   View source code 6 votes vote down vote up
Stream<Assignment> allPossible() throws Throwable {

        final List<FrameworkMethod> annotatedMethods = testClass.getAnnotatedMethods(DataProducer.class);


        Stream<Assignment> methodAssignments = Stream.empty();
        for (FrameworkMethod annotatedMethod : annotatedMethods) {
            final Type methodReturnType = getMethodGenericReturnType(annotatedMethod.getMethod());
            methodAssignments = Stream.concat(methodAssignments, methodToStreamOfResults(annotatedMethod)
                    .map(value -> new MethodResultAssignment(value, methodReturnType, annotatedMethod)));
        }

        final List<FrameworkField> annotatedFields = testClass.getAnnotatedFields(DataProducer.class);
        final Stream<Assignment> fieldsAssignments = annotatedFields.stream()
                .map(FieldAssignment::new);
        return Stream.concat(fieldsAssignments, methodAssignments);
    }
 
Example 2
Project: Reer   File: RedirectStdOutAndErr.java   View source code 6 votes vote down vote up
public Statement apply(final Statement base, FrameworkMethod method, Object target) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            originalStdOut = System.out;
            originalStdErr = System.err;
            stdOutRouter.setOut(originalStdOut);
            stdErrRouter.setOut(originalStdErr);
            try {
                System.setOut(stdOutPrintStream);
                System.setErr(stdErrPrintStream);
                base.evaluate();
            } finally {
                System.setOut(originalStdOut);
                System.setErr(originalStdErr);
                stdOutRouter = null;
                stdErrRouter = null;
                stdOutPrintStream = null;
                stdErrPrintStream = null;
                stdoutContent = null;
                stderrContent = null;
            }
        }
    };
}
 
Example 3
Project: easy-test   File: EasyJUnit4.java   View source code 6 votes vote down vote up
protected Statement methodBlock(FrameworkMethod method) {
    Object test;
    try {
        test = new ReflectiveCallable() {
            @Override
            protected Object runReflectiveCall() throws Throwable {
                return createTest();
            }
        }.run();
    } catch (Throwable e) {
        return new Fail(e);
    }

    Statement statement = methodInvoker(method, test);
    statement = possiblyExpectingExceptions(method, test, statement);
    statement = withPotentialTimeout(method, test, statement);
    statement = withBefores(method, test, statement);
    statement = withAfters(method, test, statement);
    statement = withRules(method, test, statement);
    return statement;
}
 
Example 4
Project: io-comparison   File: OrderedRunner.java   View source code 6 votes vote down vote up
@Override
protected List<FrameworkMethod> computeTestMethods() {
    List<FrameworkMethod> list = super.computeTestMethods();
    Collections.sort(list, new Comparator<FrameworkMethod>() {
        @Override
        public int compare(FrameworkMethod f1, FrameworkMethod f2) {
            Order o1 = f1.getAnnotation(Order.class);
            Order o2 = f2.getAnnotation(Order.class);

            if (o1 == null) {
                if (o2 != null) { // o1 == null, o2 != null
                    return 1;
                } else {  // o1 == null, o2 == null
                    return f1.getName().compareTo(f2.getName());
                }
            } else {
                if (o2 != null) {//o1 != null, o2 != null
                    return o1.value() - o2.value();
                } else { //o1 != null, o2 == null
                    return -1;
                }
            }
        }
    });
    return list;
}
 
Example 5
Project: oscm   File: OrderedRunner.java   View source code 6 votes vote down vote up
@Override
protected List<FrameworkMethod> computeTestMethods() {
    List<FrameworkMethod> list = super.computeTestMethods();
    List<FrameworkMethod> copy = new ArrayList<>(list);
    Collections.sort(copy, new Comparator<FrameworkMethod>() {

        @Override
        public int compare(FrameworkMethod f1, FrameworkMethod f2) {
            Order o1 = f1.getAnnotation(Order.class);
            Order o2 = f2.getAnnotation(Order.class);

            if(o1 == null || o2 == null) {
                return -1;
            }

            return o1.order() - o2.order();
        }
    });

    return copy;
}
 
Example 6
Project: spockito   File: Spockito.java   View source code 6 votes vote down vote up
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;
}
 
Example 7
Project: tubik   File: OrderedRunner.java   View source code 6 votes vote down vote up
@Override
protected List<FrameworkMethod> computeTestMethods() {
    List<FrameworkMethod> list = super.computeTestMethods();
    List<FrameworkMethod> copy = new ArrayList<FrameworkMethod>(list);
    Collections.sort(copy, new Comparator<FrameworkMethod>() {

        @Override
        public int compare(FrameworkMethod f1, FrameworkMethod f2) {
            Order o1 = f1.getAnnotation(Order.class);
            Order o2 = f2.getAnnotation(Order.class);

            if (o1 == null || o2 == null) {
                return -1;
            }

            return o1.order() - o2.order();
        }
    });
    return copy;
}
 
Example 8
Project: morf   File: InjectMembersRule.java   View source code 6 votes vote down vote up
/**
 * @see org.junit.rules.MethodRule#apply(org.junit.runners.model.Statement, org.junit.runners.model.FrameworkMethod, java.lang.Object)
 */
@Override
public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
  return new Statement() {
    @Override
    public void evaluate() throws Throwable {
      final List<Module> moduleWithTarget = new ArrayList<>(Arrays.asList(modules));
      if (target instanceof Module) {
        moduleWithTarget.add((Module) target);
      }
      Guice.createInjector(moduleWithTarget).injectMembers(target);
      try {
        base.evaluate();
      } finally {
        new ThreadSafeMockingProgress().reset();
      }
    }
  };
}
 
Example 9
Project: pact-spring-mvc   File: PactTestRunner.java   View source code 6 votes vote down vote up
@Override
protected Statement methodInvoker(final FrameworkMethod method, final Object test) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            PactFrameworkMethod pactFrameworkMethod = (PactFrameworkMethod) method;
            if (pactFrameworkMethod.shouldExclude()) {
                LOG.warn("Test has been excluded. Test will show as passed but was *NOT* run.");
                return;
            }
            if (pactFrameworkMethod.getWorkflow() != null) {
                setUpProviderState(test, pactFrameworkMethod.getWorkflow());
                pactFrameworkMethod.invokeExplosively(test, pactFrameworkMethod.getWorkflow().getInteractions());
            } else {
                setUpProviderState(test, pactFrameworkMethod.getInteraction());
                pactFrameworkMethod.invokeExplosively(test, Collections.singletonList(pactFrameworkMethod.getInteraction()));
            }
        }
    };
}
 
Example 10
Project: Bytecoder   File: BytecoderUnitTestRunner.java   View source code 6 votes vote down vote up
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);
        }
    }
}
 
Example 11
Project: cortado   File: OrderedJUnit4TestRunner.java   View source code 6 votes vote down vote up
@Override
protected List<FrameworkMethod> computeTestMethods() {
    final List<FrameworkMethod> unordered = super.computeTestMethods();
    List<FrameworkMethod> otherMethods = new ArrayList<>(unordered);
    List<FrameworkMethod> orderedMethods = new ArrayList<>();
    // extracting methods annotated ofRes Order
    for (int i = 0; i < otherMethods.size(); i++) {
        FrameworkMethod frameworkMethod = otherMethods.get(i);
        Order order = frameworkMethod.getAnnotation(Order.class);
        if (order != null) {
            orderedMethods.add(frameworkMethod);
            otherMethods.remove(i--);
        }
    }
    // sorting ordered methods
    Collections.sort(orderedMethods, new Comparator<FrameworkMethod>() {
        @Override
        public int compare(FrameworkMethod f1, FrameworkMethod f2) {
            return f1.getAnnotation(Order.class).value() -
                    f2.getAnnotation(Order.class).value();
        }
    });
    // appending other methods to ordered methods
    orderedMethods.addAll(otherMethods);
    return Collections.unmodifiableList(orderedMethods);
}
 
Example 12
Project: junit-easy-tools   File: TestObject.java   View source code 5 votes vote down vote up
Object createTestObject() throws Exception {
    List<FrameworkMethod> annotatedMethods = testClass.getAnnotatedMethods(TestFactory.class);
    if (!annotatedMethods.isEmpty()) {
        Method factoryMethod = annotatedMethods.get(0).getMethod();
        validateFactoryMethod(factoryMethod);
        return factoryMethod.invoke(null);
    }
    return testClass.getOnlyConstructor().newInstance();
}
 
Example 13
Project: junit-easy-tools   File: PotentialAssignments.java   View source code 5 votes vote down vote up
private static Stream<?> methodToStreamOfResults(FrameworkMethod annotatedMethod) {
    try {
        return ((Collection<?>) annotatedMethod.invokeExplosively(null)).stream();
    } catch (Throwable throwable) {
        throw new IllegalArgumentException(throwable);
    }
}
 
Example 14
Project: junit-easy-tools   File: JUnitEasyTools.java   View source code 5 votes vote down vote up
@Override
protected void validateTestMethods(List<Throwable> errors) {
    List<FrameworkMethod> annotatedMethods = getTestClass().getAnnotatedMethods(Test.class);
    for (FrameworkMethod annotatedMethod : annotatedMethods) {
        annotatedMethod.validatePublicVoid(false, errors);
    }
}
 
Example 15
Project: ArchUnit   File: ArchUnitRunner.java   View source code 5 votes vote down vote up
private Collection<ArchTestExecution> findArchRuleMethods() {
    List<ArchTestExecution> result = new ArrayList<>();
    for (FrameworkMethod testMethod : getTestClass().getAnnotatedMethods(ArchTest.class)) {
        result.add(new ArchTestMethodExecution(getTestClass().getJavaClass(), testMethod.getMethod(), false));
    }
    return result;
}
 
Example 16
Project: mbed-cloud-sdk-java   File: ExampleRunner.java   View source code 5 votes vote down vote up
@Override
protected List<FrameworkMethod> computeTestMethods() {
    List<FrameworkMethod> list = getTestClass().getAnnotatedMethods(Test.class);
    List<FrameworkMethod> list2 = getTestClass().getAnnotatedMethods(Example.class);
    if (list == null || list.isEmpty()) {
        return list2;
    }
    if (list2 == null || list2.isEmpty()) {
        return list;
    }
    list2.addAll(list);
    return list2;

}
 
Example 17
Project: junit-easy-tools   File: JUnitEasyToolsValidationTest.java   View source code 5 votes vote down vote up
@Test
public void shouldThrowExceptionOnNoDataProducer() throws Throwable {
    Method testMethod = NoDataProducer.class.getMethod("a", String.class);
    FrameworkMethod method = new FrameworkMethod(testMethod);
    FrameworkMethod spyMethod = spy(method);
    when(spyMethod.getAnnotation(Ignore.class)).thenReturn(null);
    assertThatExceptionOfType(InitializationError.class).isThrownBy(() ->
            new JUnitEasyTools(NoDataProducer.class).methodBlock(method).evaluate());
}
 
Example 18
Project: Reer   File: TestResources.java   View source code 5 votes vote down vote up
public Statement apply(Statement base, final FrameworkMethod method, Object target) {
    final Statement statement = resources.apply(base, method, target);
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            String className = method.getMethod().getDeclaringClass().getSimpleName();
            maybeCopy(String.format("%s/shared", className));
            maybeCopy(String.format("%s/%s", className, method.getName()));
            for (String extraResource : extraResources) {
                maybeCopy(extraResource);
            }
            statement.evaluate();
        }
    };
}
 
Example 19
Project: firebase-admin-java   File: MockitoTestRule.java   View source code 5 votes vote down vote up
@Override
public Statement apply(final Statement base, FrameworkMethod method, final Object target) {
  return new Statement() {
    @Override
    public void evaluate() throws Throwable {
      MockitoAnnotations.initMocks(target);
      try {
        base.evaluate();
      } finally {
        Mockito.validateMockitoUsage();
      }
    }
  };
}
 
Example 20
Project: n4js   File: XtextParametrizedRunner.java   View source code 5 votes vote down vote up
private FrameworkMethod getAnnotatedPublicStaticMethod(Class<? extends Annotation> anno) {
	List<FrameworkMethod> methods = getTestClass().getAnnotatedMethods(anno);
	for (FrameworkMethod each : methods) {
		if (each.isStatic() && each.isPublic()) {
			return each;
		}
	}
	return null;
}
 
Example 21
Project: n4js   File: XtextParametrizedRunner.java   View source code 5 votes vote down vote up
/**
 * Implements behavior from: org.junit.runners.Parameterized
 */
private Exception parametersMethodReturnedWrongType(FrameworkMethod parametersMethod) throws Exception {
	String className = getTestClass().getName();
	String message = MessageFormat.format("{0}.{1}() must return an Iterable of arrays.", className,
			parametersMethod.getName());
	return new Exception(message);
}
 
Example 22
Project: n4js   File: XtextParametrizedRunner.java   View source code 5 votes vote down vote up
private Exception parametersProviderMethodReturnedWrongType(FrameworkMethod parametersMethod) throws Exception {
	String className = getTestClass().getName();
	String message = MessageFormat.format("{0}.{1}() must return an Provider for an Iterable of arrays.",
			className,
			parametersMethod.getName());
	return new Exception(message);
}
 
Example 23
Project: n4js   File: XtextParametrizedRunner.java   View source code 5 votes vote down vote up
private Exception unexpectedArrayElement() throws Exception {
	FrameworkMethod method = getParametersMethod();
	if (method != null) {
		return parametersMethodReturnedWrongType(method);
	}
	return parametersProviderMethodReturnedWrongType(getParametersProviderMethod());
}
 
Example 24
Project: easy-test   File: EasyJUnit4.java   View source code 5 votes vote down vote up
private Statement withRules(FrameworkMethod method, Object target,
                            Statement statement) {
    List<TestRule> testRules = getTestRules(target);
    Statement result = statement;
    result = withMethodRules(method, testRules, target, result);
    result = withTestRules(method, testRules, result);

    return result;
}
 
Example 25
Project: dockerunit   File: DockerUnitRunner.java   View source code 5 votes vote down vote up
private void validateNoOrOneServiceContextArg(FrameworkMethod testMethod, List<Throwable> errors) {
	if (testMethod.getMethod().getParameterCount() > 0
			&& !testMethod.getMethod().getParameterTypes()[0].isAssignableFrom(ServiceContext.class)) {
		errors.add(new Exception("Test method " + testMethod.getName()
				+ "() must have either zero args or one arg of type " + ServiceContext.class.getName()));
	}
}
 
Example 26
Project: testee.fi   File: TestEEfi.java   View source code 5 votes vote down vote up
@Override
protected Statement withBefores(
        final FrameworkMethod method,
        final Object target,
        final Statement statement
) {
    createInstanceFor(method, target);
    return super.withBefores(method, target, statement);
}
 
Example 27
Project: testee.fi   File: TestEEfi.java   View source code 5 votes vote down vote up
private synchronized void createInstanceFor(final FrameworkMethod method, final Object target) {
    final String instanceId = target.getClass().getName()
            + ":"
            + method.getMethod().toString()
            + ":"
            + System.identityHashCode(target);
    final TestSetup.TestInstance context = testSetup.prepareTestInstance(instanceId, target, method.getMethod());
    instances.put(method, context);

}
 
Example 28
Project: testee.fi   File: TestEEfi.java   View source code 5 votes vote down vote up
@Override
protected void runChild(FrameworkMethod method, RunNotifier notifier) {
    try {
        super.runChild(method, notifier);
    } finally {
        shutdownInstanceFor(method);
    }
}
 
Example 29
Project: JUnitWithParams   File: WithParamsRule.java   View source code 5 votes vote down vote up
ParameterizedStatement(final Set<String> executedTests, final HashMap<String, String> paramsMap,
                       final FrameworkMethod method, final Statement base, final ErrorCollector errorCollector,
                       HashSet<String> usedParams) {
    mMethod = method;
    mBase = base;
    this.mExecutedTests = executedTests;
    this.mParamsMap = paramsMap;
    this.errorCollector = errorCollector;
    this.usedParams = usedParams;
}
 
Example 30
Project: io-comparison   File: FocusRunner.java   View source code 5 votes vote down vote up
@Override
protected List<FrameworkMethod> getChildren() {
    List<FrameworkMethod> tests = super.getChildren();
    List<FrameworkMethod> focuses = getTestClass().getAnnotatedMethods(Focus.class);
    focuses.retainAll(tests);
    if (focuses.isEmpty()) {
        exceptEnabled = false;
        return tests;
    } else {
        exceptEnabled = true;
        return focuses;
    }
}
 
Example 31
Project: shabdiz   File: ExperimentRunner.java   View source code 5 votes vote down vote up
private List<Description> getMethodDescriptions(final Runner runner) {

        final String displayName = runner.getDescription().getDisplayName();
        final List<FrameworkMethod> methods = getTestClass().getAnnotatedMethods(Test.class);
        List<Description> descriptions = new ArrayList<Description>();
        for (FrameworkMethod method : methods) {
            final Description description = Description.createTestDescription(getTestClass().getJavaClass(), method.getName() + displayName, method.getAnnotations());
            descriptions.add(description);
        }

        return descriptions;
    }
 
Example 32
Project: shabdiz   File: ParallelParameterized.java   View source code 5 votes vote down vote up
private FrameworkMethod getHostProviderMethodByName(final String host_provider_name) {

        for (FrameworkMethod provider : getTestClass().getAnnotatedMethods(HostProvider.class)) {
            if (provider.getAnnotation(HostProvider.class).name().equals(host_provider_name)) { return provider; }
        }

        return null;
    }
 
Example 33
Project: shabdiz   File: ParallelParameterized.java   View source code 5 votes vote down vote up
private List<Description> getMethodDescriptions(final Runner runner) {

        final String displayName = runner.getDescription().getDisplayName();
        final List<FrameworkMethod> methods = getTestClass().getAnnotatedMethods(Test.class);
        List<Description> descriptions = new ArrayList<Description>();
        for (FrameworkMethod method : methods) {
            final Description description = Description.createTestDescription(getTestClass().getJavaClass(), method.getName() + displayName, method.getAnnotations());
            descriptions.add(description);
        }

        return descriptions;
    }
 
Example 34
Project: java-red   File: RedTestRunner.java   View source code 5 votes vote down vote up
@Override
protected void validateTestMethods(List<Throwable> errors) {
    List<FrameworkMethod> methods = getTestClass().getAnnotatedMethods(Test.class);
    for (FrameworkMethod method : methods) {
        method.validatePublicVoid(false, errors);
        if (!isNormalTest(method) && !isAsyncTest(method)) {
            errors.add(new Exception("Method " + method.getName() + " can either have no parameters, or" +
                    "one AsyncTest parameter"));
        }
    }
}
 
Example 35
Project: Rubus   File: OrderedTestRunner.java   View source code 5 votes vote down vote up
@Override
protected List<FrameworkMethod> computeTestMethods() {
    // get all methods to be tested
    List<FrameworkMethod> toSort = super.computeTestMethods();
 
    if (toSort.isEmpty())
        return toSort;
 
    // a map containing <line_number, method>
    final Map<Integer, FrameworkMethod> testMethods = new TreeMap<Integer, FrameworkMethod> ();
 
    // check that all methods here are declared in the same class, we don't
    // deal with test methods from superclasses that haven't been overridden
    Class<?> clazz = getDeclaringClass(toSort);
    if (clazz == null) {
        // fail explicitly
        System.err
                .println("OrderedTestRunner can only run test classes that"
                        + " don't have test methods inherited from superclasses");
        return Collections.emptyList();
    }
 
    // use Javassist to figure out line numbers for methods
    ClassPool pool = ClassPool.getDefault();
    try {
        CtClass cc = pool.get(clazz.getName());
        // all methods in toSort are declared in the same class, we checked
        for (FrameworkMethod m : toSort) {
            String methodName = m.getName();
            CtMethod method = cc.getDeclaredMethod(methodName);
            testMethods.put(method.getMethodInfo().getLineNumber(0), m);
        }
    } catch (NotFoundException e) {
        e.printStackTrace();
    }
 
    return new ArrayList<FrameworkMethod>(testMethods.values());
}
 
Example 36
Project: Rubus   File: OrderedTestRunner.java   View source code 5 votes vote down vote up
private Class<?> getDeclaringClass(List<FrameworkMethod> methods) {
    // methods can't be empty, it's been checked
    Class<?> clazz = methods.get(0).getMethod().getDeclaringClass();
 
    for (int i = 1; i < methods.size(); i++) {
        if (!methods.get(i).getMethod().getDeclaringClass().equals(clazz)) {
            // they must be all in the same class
            return null;
        }
    }
 
    return clazz;
}
 
Example 37
Project: ZooKeeper   File: ZKTestCase.java   View source code 5 votes vote down vote up
@Override
public void starting(FrameworkMethod method) {
    testName = method.getName();
    // ZOOKEEPER-2693 disables all 4lw by default.
    // Here we enable the 4lw which ZooKeeper tests depends.
    System.setProperty("zookeeper.4lw.commands.whitelist", "*");

    LOG.info("STARTING " + testName);
}
 
Example 38
Project: ArchUnit   File: ArchTestMethodExecution.java   View source code 5 votes vote down vote up
private void executeTestMethod(JavaClasses classes) throws Throwable {
    if (!Arrays.equals(testMethod.getParameterTypes(), new Class<?>[]{JavaClasses.class})) {
        throw new IllegalArgumentException(String.format(
                "Methods annotated with @%s must have exactly one parameter of type %s",
                ArchTest.class.getSimpleName(), JavaClasses.class.getSimpleName()));
    }

    new FrameworkMethod(testMethod).invokeExplosively(testClass.newInstance(), classes);
}
 
Example 39
Project: spockito   File: AbstractSpockitoTestRunner.java   View source code 5 votes vote down vote up
@Override
protected Description describeChild(final FrameworkMethod method) {
    final Spockito.Name name = Spockito.nameAnnotationOrNull(method.getMethod());
    if (name != null && name.shortFormat()) {
        return Description.createSuiteDescription(testName(method), method.getAnnotations());
    } else {
        return super.describeChild(method);
    }
}
 
Example 40
Project: spockito   File: SingleTestMultiRowRunner.java   View source code 5 votes vote down vote up
@Override
protected String testName(final FrameworkMethod method) {
    if (method instanceof UnrolledTestMethod) {
        return method.getName() + Spockito.getName(method.getMethod(), ((UnrolledTestMethod)method).getTableRow());
    }
    return super.testName(method);
}