Optional<Method> findMethod(String methodSpecPart, Class<?> clazz) { Matcher matcher = METHOD_PATTERN.matcher(methodSpecPart); Preconditions.condition(matcher.matches(), () -> String.format("Method [%s] does not match pattern [%s]", methodSpecPart, METHOD_PATTERN)); String methodName = matcher.group(1); String parameterTypeNames = matcher.group(2); return ReflectionUtils.findMethod(clazz, methodName, parameterTypeNames); }
private void resolveContainedMethods(TestDescriptor containerDescriptor, Class<?> testClass) { List<Method> testMethodCandidates = findMethods(testClass, ReflectionUtils::isNotPrivate); testMethodCandidates.forEach(method -> resolve(method, containerDescriptor)); }
private static Function<String, Object> findFactoryExecutable(Class<?> targetType) { return factoryExecutableCache.computeIfAbsent(targetType, type -> { Method factoryMethod = findFactoryMethod(type); if (factoryMethod != null) { return source -> invokeMethod(factoryMethod, null, source); } Constructor<?> constructor = findFactoryConstructor(type); if (constructor != null) { return source -> newInstance(constructor, source); } return NULL_EXECUTABLE; }); }
protected Object executeMethod(String methodName, Class<?>[] parameterTypes, Object... arguments) { Method method = findMethod(this.target.getClass(), methodName, parameterTypes).orElseThrow( () -> new JUnitException(String.format("Failed to find method %s(%s) in class %s", methodName, ClassUtils.nullSafeToString(parameterTypes), this.target.getClass().getName()))); return invokeMethod(method, this.target, arguments); }
/** * Invoke the supplied {@code static} method with dynamic parameter resolution. * * @param method the method to invoke and resolve parameters for * @param extensionContext the current {@code ExtensionContext} * @param extensionRegistry the {@code ExtensionRegistry} to retrieve * {@code ParameterResolvers} from */ public Object invoke(Method method, ExtensionContext extensionContext, ExtensionRegistry extensionRegistry) { return ReflectionUtils.invokeMethod(method, null, resolveParameters(method, Optional.empty(), extensionContext, extensionRegistry)); }
private static Predicate<? super Throwable> createAbortedExecutionPredicate() { Predicate<Throwable> otaPredicate = TestAbortedException.class::isInstance; // Additionally support JUnit 4's AssumptionViolatedException? Class<?> clazz = ReflectionUtils.tryToLoadClass( "org.junit.internal.AssumptionViolatedException").toOptional().orElse(null); if (clazz != null) { return otaPredicate.or(clazz::isInstance); } // Else just OTA's TestAbortedException return otaPredicate; }
/** * Invoke the supplied constructor with dynamic parameter resolution. * * @param constructor the constructor to invoke and resolve parameters for * @param extensionContext the current {@code ExtensionContext} * @param extensionRegistry the {@code ExtensionRegistry} to retrieve * {@code ParameterResolvers} from */ public <T> T invoke(Constructor<T> constructor, ExtensionContext extensionContext, ExtensionRegistry extensionRegistry) { return ReflectionUtils.newInstance(constructor, resolveParameters(constructor, Optional.empty(), extensionContext, extensionRegistry)); }
@Override public void afterEach(ExtensionContext extensionContext) throws Exception { final Object testInstance = extensionContext.getTestInstance() .orElseThrow(() -> new IllegalStateException("Unable to get the current test instance")); try { for (Field member : findAnnotatedFields(testInstance.getClass(), false)) { ((DropwizardExtension) ReflectionUtils.makeAccessible(member).get(testInstance)).after(); } } catch (Throwable e) { throw new RuntimeException(e); } }
@Override public ParallelExecutionConfiguration createConfiguration(ConfigurationParameters configurationParameters) { String className = configurationParameters.get(CONFIG_CUSTOM_CLASS_PROPERTY_NAME).orElseThrow( () -> new JUnitException(CONFIG_CUSTOM_CLASS_PROPERTY_NAME + " must be set")); return ReflectionUtils.tryToLoadClass(className) // .andThenTry(strategyClass -> { Preconditions.condition( ParallelExecutionConfigurationStrategy.class.isAssignableFrom(strategyClass), CONFIG_CUSTOM_CLASS_PROPERTY_NAME + " does not implement " + ParallelExecutionConfigurationStrategy.class); return (ParallelExecutionConfigurationStrategy) ReflectionUtils.newInstance(strategyClass); }) // .andThenTry(strategy -> strategy.createConfiguration(configurationParameters)) // .getOrThrow(cause -> new JUnitException( "Could not create configuration for strategy class: " + className, cause)); } };
@Override public void resolve(EngineDiscoveryRequest request, ClassFilter classFilter, TestClassCollector collector) { // @formatter:off request.getSelectorsByType(ClasspathRootSelector.class) .stream() .map(ClasspathRootSelector::getClasspathRoot) .map(root -> findAllClassesInClasspathRoot(root, classFilter)) .flatMap(Collection::stream) .forEach(collector::addCompletely); // @formatter:on }
@Override public void resolve(EngineDiscoveryRequest request, ClassFilter classFilter, TestClassCollector collector) { // @formatter:off request.getSelectorsByType(PackageSelector.class) .stream() .map(PackageSelector::getPackageName) .map(packageName -> findAllClassesInPackage(packageName, classFilter)) .flatMap(Collection::stream) .forEach(collector::addCompletely); // @formatter:on }
@Override public void resolve(EngineDiscoveryRequest request, ClassFilter classFilter, TestClassCollector collector) { // @formatter:off request.getSelectorsByType(ModuleSelector.class) .stream() .map(ModuleSelector::getModuleName) .map(moduleName -> findAllClassesInModule(moduleName, classFilter)) .flatMap(Collection::stream) .forEach(collector::addCompletely); // @formatter:on }
protected Object executeMethod(String methodName, Class<?>[] parameterTypes, Object... arguments) { Method method = findMethod(this.target.getClass(), methodName, parameterTypes).orElseThrow( () -> new JUnitException(String.format("Failed to find method %s(%s) in class %s", methodName, StringUtils.nullSafeToString(parameterTypes), this.target.getClass().getName()))); return invokeMethod(method, this.target, arguments); }
@Override public Stream<Arguments> provideArguments(ExtensionContext context) { Object testInstance = context.getTestInstance().orElse(null); // @formatter:off return Arrays.stream(this.methodNames) .map(factoryMethodName -> getMethod(context, factoryMethodName)) .map(method -> ReflectionUtils.invokeMethod(method, testInstance)) .flatMap(CollectionUtils::toStream) .map(MethodArgumentsProvider::toArguments); // @formatter:on }
private static Class<?> toClass(String type) { //@formatter:off return ReflectionUtils .tryToLoadClass(type) .getOrThrow(cause -> new ArgumentConversionException( "Failed to convert String \"" + type + "\" to type " + Class.class.getName(), cause)); //@formatter:on }
/** * Invoke the supplied constructor with the supplied outer instance and * dynamic parameter resolution. * * <p>This method should only be used to invoke the constructor for * an inner class. * * @param constructor the constructor to invoke and resolve parameters for * @param outerInstance the outer instance to supply as the first argument * to the constructor * @param extensionContext the current {@code ExtensionContext} * @param extensionRegistry the {@code ExtensionRegistry} to retrieve * {@code ParameterResolvers} from */ public <T> T invoke(Constructor<T> constructor, Object outerInstance, ExtensionContext extensionContext, ExtensionRegistry extensionRegistry) { return ReflectionUtils.newInstance(constructor, resolveParameters(constructor, Optional.empty(), outerInstance, extensionContext, extensionRegistry)); }
@Override public void beforeEach(ExtensionContext extensionContext) throws Exception { final Object testInstance = extensionContext.getTestInstance() .orElseThrow(() -> new IllegalStateException("Unable to get the current test instance")); try { for (Field member : findAnnotatedFields(testInstance.getClass(), false)) { ((DropwizardExtension) ReflectionUtils.makeAccessible(member).get(testInstance)).before(); } } catch (Throwable e) { throw new RuntimeException(e); } } }
void resolveClasspathRoot(ClasspathRootSelector selector) { try { findAllClassesInClasspathRoot(selector.getClasspathRoot(), this.classFilter).forEach(this::resolveClass); } catch (Throwable t) { rethrowIfBlacklisted(t); logger.debug(t, () -> format("Failed to resolve classes in classpath root '%s'.", selector.getClasspathRoot())); } }
void resolvePackage(PackageSelector selector) { try { findAllClassesInPackage(selector.getPackageName(), this.classFilter).forEach(this::resolveClass); } catch (Throwable t) { rethrowIfBlacklisted(t); logger.debug(t, () -> format("Failed to resolve classes in package '%s'.", selector.getPackageName())); } }
void resolveModule(ModuleSelector selector) { try { findAllClassesInModule(selector.getModuleName(), this.classFilter).forEach(this::resolveClass); } catch (Throwable t) { rethrowIfBlacklisted(t); logger.debug(t, () -> format("Failed to resolve classes in module '%s'.", selector.getModuleName())); } }