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); }
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; } } }; }
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; }
@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; }
@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; }
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; }
@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; }
/** * @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(); } } }; }
@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())); } } }; }
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); } } }
@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); }
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(); }
private static Stream<?> methodToStreamOfResults(FrameworkMethod annotatedMethod) { try { return ((Collection<?>) annotatedMethod.invokeExplosively(null)).stream(); } catch (Throwable throwable) { throw new IllegalArgumentException(throwable); } }
@Override protected void validateTestMethods(List<Throwable> errors) { List<FrameworkMethod> annotatedMethods = getTestClass().getAnnotatedMethods(Test.class); for (FrameworkMethod annotatedMethod : annotatedMethods) { annotatedMethod.validatePublicVoid(false, errors); } }
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; }
@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; }
@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()); }
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(); } }; }
@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(); } } }; }
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; }
/** * 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); }
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); }
private Exception unexpectedArrayElement() throws Exception { FrameworkMethod method = getParametersMethod(); if (method != null) { return parametersMethodReturnedWrongType(method); } return parametersProviderMethodReturnedWrongType(getParametersProviderMethod()); }
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; }
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())); } }
@Override protected Statement withBefores( final FrameworkMethod method, final Object target, final Statement statement ) { createInstanceFor(method, target); return super.withBefores(method, target, statement); }
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); }
@Override protected void runChild(FrameworkMethod method, RunNotifier notifier) { try { super.runChild(method, notifier); } finally { shutdownInstanceFor(method); } }
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; }
@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; } }
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; }
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; }
@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")); } } }
@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()); }
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; }
@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); }
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); }
@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); } }
@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); }