Java 类org.junit.jupiter.api.extension.ParameterResolutionException 实例源码

项目:autotest    文件:AutoTestParameterResolver.java   
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
        throws ParameterResolutionException {
    Object argument = arguments[parameterContext.getIndex()];
    Parameter parameter = parameterContext.getParameter();
    Optional<ConvertWith> annotation = AnnotationUtils.findAnnotation(parameter, ConvertWith.class);
    // @formatter:off
    ArgumentConverter argumentConverter = annotation.map(ConvertWith::value)
            .map(clazz -> (ArgumentConverter) ReflectionUtils.newInstance(clazz))
            .map(converter -> AnnotationConsumerInitializer.initialize(parameter, converter))
            .orElse(DefaultArgumentConverter.INSTANCE);
    // @formatter:on
    try {
        return argumentConverter.convert(argument, parameterContext);
    } catch (Exception ex) {
        throw new ParameterResolutionException("参数转换出错:" + parameter.getType().getName(),
                ex);
    }
}
项目:junit5-extensions    文件:MockitoExtension.java   
@Override
public Object resolveParameter(ParameterContext parameterContext,
    ExtensionContext extensionContext)
    throws ParameterResolutionException {
  List<ParameterFactory> validFactories =
      getSupportedFactories(parameterContext.getParameter()).collect(toList());

  if (validFactories.size() > 1) {
    throw new ParameterResolutionException(
        String.format("Too many factories: %s for parameter: %s",
            validFactories,
            parameterContext.getParameter()));
  }

  return Iterables.getOnlyElement(validFactories)
      .getParameterValue(parameterContext.getParameter());
}
项目:vaadin-016-helloworld-14    文件:PageObjectExtension.java   
@Override
//  public AbstractVaadinPageObject resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
  public AbstractVaadinPageObject resolve(ParameterContext parameterContext, ExtensionContext extensionContext)
      throws ParameterResolutionException {

    Supplier<WebDriver> webDriverSupplier = webdriver().apply(extensionContext);

    Class<?> pageObject = parameterContext.getParameter().getType();
    try {
      Constructor<?> constructor =
          pageObject.getConstructor(WebDriver.class);
      return AbstractVaadinPageObject.class.cast(constructor.newInstance(webDriverSupplier.get()));
    } catch (NoSuchMethodException
        | IllegalAccessException
        | InstantiationException
        | InvocationTargetException e) {
      e.printStackTrace();
      throw new ParameterResolutionException("was not able to create PageObjectInstance ", e);
    }
  }
项目:resp-server    文件:CommandRule.java   
public void init() throws ParameterResolutionException {
  server = mock(ServerContext.class);
  request = mock(Request.class);
  session = mock(Session.class);

  when(request.getServerContext()).thenReturn(server);
  when(request.getSession()).thenReturn(session);
  when(session.getId()).thenReturn("localhost:12345");

  MockitoAnnotations.initMocks(target);

  try {
    command = target.getClass().getAnnotation(CommandUnderTest.class).value().newInstance();
  } catch (InstantiationException | IllegalAccessException e) {
    throw new ParameterResolutionException("error", e);
  }
}
项目:junit-dataprovider    文件:AbstractUseDataProviderArgumentProviderTest.java   
@Test
void testInvokeDataProviderMethodToRetrieveDataShouldThrowParameterResolutionExceptionIfDataProviderInvocationThrows()
        throws Exception {
    // Given:
    Method dataProviderMethod = this.getClass().getDeclaredMethod(
            "testInvokeDataProviderMethodToRetrieveDataShouldThrowParameterResolutionExceptionIfDataProviderInvocationThrows");

    when(extensionContext.getRoot()).thenReturn(extensionContext);
    when(extensionContext.getStore(any(Namespace.class))).thenReturn(store);

    // When:
    Exception result = assertThrows(ParameterResolutionException.class,
            () -> underTest.invokeDataProviderMethodToRetrieveData(dataProviderMethod, true, extensionContext));

    // Then:
    assertThat(result).hasMessageMatching("Exception while invoking dataprovider method '.*': .*");
}
项目:weld-junit    文件:WeldJunit5Extension.java   
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
    // we did our checks in supportsParameter() method, now we can do simple resolution
    if (getContainerFromStore(extensionContext) != null) {
        List<Annotation> qualifiers = resolveQualifiers(parameterContext, getContainerFromStore(extensionContext).getBeanManager());
        return getContainerFromStore(extensionContext)
            .select(parameterContext.getParameter().getType(), qualifiers.toArray(new Annotation[qualifiers.size()])).get();
    }
    return null;
}
项目:weld-junit    文件:WeldJunit5Extension.java   
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
    // if weld container isn't up yet or if its not Method, we don't resolve it
    if (getContainerFromStore(extensionContext) == null || (!(parameterContext.getDeclaringExecutable() instanceof Method))) {
        return false;
    }
    List<Annotation> qualifiers = resolveQualifiers(parameterContext, getContainerFromStore(extensionContext).getBeanManager());
    // if we require explicit parameter injection (via global settings or annotation) and there are no qualifiers we don't resolve it
    if ((getExplicitInjectionInfoFromStore(extensionContext) || (methodRequiresExplicitParamInjection(parameterContext))) && qualifiers.isEmpty()) {
        return false;
    } else {
        return getContainerFromStore(extensionContext).select(parameterContext.getParameter().getType(), qualifiers.toArray(new Annotation[qualifiers.size()]))
            .isResolvable();
    }
}
项目:junit5-extensions    文件:UsageExampleTests.java   
@ExpectFailure({
    @Cause(type = ParameterResolutionException.class),
    @Cause(type = ArgumentConversionException.class),
    @Cause(type = ClassNotFoundException.class)
})
@ParameterizedTest
@ValueSource(strings = "123ClassDoesNotExist")
void classNotFound(@ConvertWith(ClassArgumentConverter.class) Class<?> clazz) {}
项目:junit5-extensions    文件:UsageExampleTests.java   
@ExpectFailure({
    @Cause(type = ParameterResolutionException.class),
    @Cause(type = ArgumentConversionException.class, message = "Invalid parameter type")
})
@ParameterizedTest
@ValueSource(strings = "java.lang.Object")
void badParameterType(@ConvertWith(ClassArgumentConverter.class) String clazz) {}
项目:junit5-extensions    文件:UsageExampleTests.java   
@ExpectFailure({
    @Cause(type = ParameterResolutionException.class),
    @Cause(
        type = ArgumentConversionException.class,
        message = "java.lang.Class<java.util.List> is not assignable to"
            + " java.lang.Class<java.util.Collection<?>>"
    )
})
@ParameterizedTest
@ValueSource(strings = "java.util.List")
void wrongClass(@ConvertWith(ClassArgumentConverter.class) Class<Collection<?>> clazz) {}
项目:junit5-extensions    文件:UsageExampleTests.java   
@ExpectFailure({
    @Cause(type = ParameterResolutionException.class),
    @Cause(type = ArgumentConversionException.class, message = "is not assignable to")
})
@ParameterizedTest
@ValueSource(strings = "java.util.List")
void badLowerBound(
    @ConvertWith(ClassArgumentConverter.class) Class<? super Collection<?>> clazz) {}
项目:junit5-extensions    文件:UsageExampleTests.java   
@ExpectFailure({
    @Cause(type = ParameterResolutionException.class),
    @Cause(type = ArgumentConversionException.class, message = "is not assignable to")
})
@ParameterizedTest
@ValueSource(strings = "java.lang.Object")
void badUpperBound(
    @ConvertWith(ClassArgumentConverter.class) Class<? extends Collection<?>> clazz) {}
项目:junit5-extensions    文件:GuiceExtension.java   
@Override
public boolean supportsParameter(ParameterContext parameterContext,
    ExtensionContext extensionContext)
    throws ParameterResolutionException {
  Parameter parameter = parameterContext.getParameter();
  if (getBindingAnnotations(parameter).size() > 1) {
    return false;
  }

  Key<?> key = getKey(
      extensionContext.getTestClass(),
      parameter);
  Optional<Injector> optInjector = getInjectorForParameterResolution(extensionContext);
  return optInjector.map(injector -> injector.getExistingBinding(key)).isPresent();
}
项目:junit5-extensions    文件:GuiceExtension.java   
@Override
public Object resolveParameter(ParameterContext parameterContext,
    ExtensionContext extensionContext)
    throws ParameterResolutionException {
  Parameter parameter = parameterContext.getParameter();
  Key<?> key = getKey(extensionContext.getTestClass(), parameter);
  Injector injector = getInjectorForParameterResolution(extensionContext)
      .orElseThrow(() ->
          new ParameterResolutionException(
              String.format(
                  "Could not create injector for: %s It has no annotated element.",
                  extensionContext.getDisplayName())));

  return injector.getInstance(key);
}
项目:junit5-extensions    文件:GuiceExtensionTest.java   
@ExpectFailure({
    @Cause(
        type = ParameterResolutionException.class,
        message = "Could not find a suitable constructor"
    ),
    @Cause(type = NoSuchMethodException.class, message = "BadModule1.<init>()")
})
@Test
@IncludeModule(BadModule1.class)
void moduleWithoutZeroArgConstructor(String string) {}
项目:junit5-extensions    文件:GuiceExtensionTest.java   
@ExpectFailure({
    @Cause(
        type = ParameterResolutionException.class,
        message = "constructor threw an exception"),
    @Cause(type = InvocationTargetException.class),
    @Cause(type = IllegalArgumentException.class, message = BadModule2.MESSAGE)
})
@Test
@IncludeModule(BadModule2.class)
void moduleConstructorThrowsException(String string) {}
项目:verify-matching-service-adapter    文件:ApplicationConfigurationResolver.java   
@Override
public ApplicationConfiguration resolveParameter(
    ParameterContext parameterContext,
    ExtensionContext extensionContext
) throws ParameterResolutionException {
    return getConfiguration();
}
项目:verify-matching-service-adapter    文件:FilesLocatorResolver.java   
@Override
public FilesLocator resolveParameter(
    ParameterContext parameterContext,
    ExtensionContext extensionContext
) throws ParameterResolutionException {
    if (applicationFilesLocator == null) {
        applicationFilesLocator = new ScenarioFilesLocator(null);
    }

    return applicationFilesLocator;
}
项目:pdfcompare    文件:TempDirectoryExtension.java   
private Path createTempDirectory(final String parentPath, ExtensionContext context) {
    try {
        if (parentPath.length() > 0) {
            return Files.createTempDirectory(Paths.get(parentPath), getDirName(context));
        } else {
            return Files.createTempDirectory(getDirName(context));
        }
    } catch (IOException e) {
        throw new ParameterResolutionException("Could not create temp directory", e);
    }
}
项目:histone-java2    文件:StringParamResolver.java   
@Override
public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
    if (extensionContext.getTestClass().isPresent()) {
        CasePack pack = extensionContext.getTestClass().get().getAnnotation(CasePack.class);
        return pack.value();
    }
    return null;
}
项目:Lyrics    文件:ConfigurationExtension.java   
@Override
public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
    String tuneType = parameterContext.getParameter().getAnnotation(TuneProvider.class).value();
    switch (tuneType) {
        case DEFAULT:
            return getDefaultTune();
        case JACKSON:
            return getJacksonTune();
        case INTERFACES:
            return getInterfacesTune();
        case NO_MODIFIERS:
            return getNoModifiersTune();
        case REQUIRED:
            return getRequiredTune();
        case JSR_303:
            return getJsr303Tune();
        case JSR_305:
            return getJsr305Tune();
        case GSON:
            return getGsonTune();
        case ANNOTATIONS:
            return getAnnotationsTune();
        case ADDITIONAL_FIELD_PROPERTY_HANDLER:
            return getAdditionalFieldPropertiesHandlerTune();
        default:
            return null;
    }
}
项目:Lyrics    文件:ConfigurationExtension.java   
@Override
public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
    String tuneType = parameterContext.getParameter().getAnnotation(TuneProvider.class).value();
    switch (tuneType) {
        case DEFAULT:
            return getDefaultTune();
        case JACKSON:
            return getJacksonTune();
        case INTERFACES:
            return getInterfacesTune();
        case NO_MODIFIERS:
            return getNoModifiersTune();
        case REQUIRED:
            return getRequiredTune();
        case JSR_303:
            return getJsr303Tune();
        case JSR_305:
            return getJsr305Tune();
        case ANDROID_SUPPORT:
            return getAndroidSpportTune();
        case GSON:
            return getGsonTune();
        case ANNOTATIONS:
            return getAnnotationsTune();
        case ADDITIONAL_FIELD_PROPERTY_HANDLER:
            return getAdditionalFieldPropertiesHandlerTune();
        default:
            return null;
    }
}
项目:demo-junit-5    文件:RandomProvider.java   
@Override
public boolean supports(
        ParameterContext parameterContext, ExtensionContext extensionContext)
        throws ParameterResolutionException {
    Class<?> targetType = parameterContext.getParameter().getType();
    return targetType == Random.class || targetType == SeededRandom.class;
}
项目:demo-junit-5    文件:RandomProvider.java   
@Override
public Object resolve(
        ParameterContext parameterContext, ExtensionContext context)
        throws ParameterResolutionException {
    return randomByUniqueId(context)
            .computeIfAbsent(context.getUniqueId(), SeededRandom::create);
}
项目:JUnit-5-Quick-Start-Guide-with-AssertJ-Spring-TestFX-Mockito    文件:RootElementResolver.java   
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
    AnnotatedElement annotatedElement = extensionContext.getElement().orElse(null);

    if (annotatedElement == null) return null;

    UITest annotation = annotatedElement.getAnnotation(UITest.class);
    FXMLLoader loader = new FXMLLoader(getClass().getResource(annotation.value()));

    try {
        return loader.load();
    } catch (IOException e) {
        return null;
    }
}
项目:JUnit-5-Quick-Start-Guide-with-AssertJ-Spring-TestFX-Mockito    文件:ClassName_ParameterResolver.java   
/**
 * Simple example that simply resolves the Parameter by returning the Class-Name based on the Parameter-Context.
 */
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
    Class<?> contextClass = extensionContext.getTestClass().orElse(null);

    return contextClass == null ? null : contextClass.getSimpleName();
}
项目:gstrap    文件:GuiceExtension.java   
@Override
public boolean supportsParameter(final ParameterContext parameterContext, final ExtensionContext extensionContext) throws ParameterResolutionException {
    final Parameter parameter = parameterContext.getParameter();
    if (getBindingAnnotations(parameter).size() > 1)
        return false;

    final Injector injector = getInjector(extensionContext);
    if (injector == null)
        return false;

    final Key<?> key = getKey(parameter);

    return injector.getExistingBinding(key) != null;
}
项目:gstrap    文件:GuiceExtension.java   
@Override
public Object resolveParameter(final ParameterContext parameterContext, final ExtensionContext extensionContext) throws ParameterResolutionException {
    final Parameter parameter = parameterContext.getParameter();
    final Key<?> key = getKey(parameter);
    final Injector injector = getInjector(extensionContext);

    return injector.getInstance(key);

}
项目:resp-server    文件:CommandRuleExtension.java   
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
    throws ParameterResolutionException {
  CommandRule commandRule = new CommandRule(
          parameterContext.getTarget().orElseThrow(() -> new ParameterResolutionException("no target")));
  commandRule.init();
  return commandRule;
}
项目:fyodor    文件:TemporalityParameterResolver.java   
@Override
public boolean supportsParameter(final ParameterContext parameterContext,
                                 final ExtensionContext extensionContext) throws ParameterResolutionException {
    final Parameter parameter = parameterContext.getParameter();

    return parameter.getType().equals(Temporality.class)
            || isSupportedJavaTimeParameterWithCurrentAnnotation(parameter);
}
项目:GitToolBox    文件:ExtensionContextParamResolver.java   
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
    throws ParameterResolutionException {
  Optional<Object> resolved = parameterTypes.stream()
      .filter(type -> supportsParameter(parameterContext, type))
      .map(type -> extensionContext.getStore(namespace).get(type, type))
      .map(Object.class::cast)
      .findFirst();
  return resolved.orElseGet(() -> parent.resolveParameter(parameterContext, extensionContext));
}
项目:junit-dataprovider    文件:AbstractUseDataProviderArgumentProvider.java   
/**
 * Retrieves the test data from given dataprovider method.
 *
 * @param dataProviderMethod the dataprovider method that gives the parameters; never {@code null}
 * @param cacheDataProviderResult determines if the dataprovider result should be cached using
 *            {@code dataProviderMethod} as key
 * @param context the execution context to use to create a {@link TestInfo} if required; never {@code null}
 *
 * @return a list of methods, each method bound to a parameter combination returned by the dataprovider
 * @throws NullPointerException if and only if one of the given arguments is {@code null}
 */
protected Object invokeDataProviderMethodToRetrieveData(Method dataProviderMethod, boolean cacheDataProviderResult,
        ExtensionContext context) {
    checkNotNull(dataProviderMethod, "'dataProviderMethod' must not be null");
    checkNotNull(context, "'context' must not be null");

    Store store = context.getRoot().getStore(NAMESPACE_USE_DATAPROVIDER);

    Object cached = store.get(dataProviderMethod);
    if (cached != null) {
        return cached;
    }
    try {
        // TODO how to not require junit-jupiter-engine dependency and reuse already existing ExtensionRegistry?
        ExtensionRegistry extensionRegistry = createRegistryWithDefaultExtensions(emptyConfigurationParameters());
        Object data = executableInvoker.invoke(dataProviderMethod, context.getTestInstance().orElse(null), context,
                extensionRegistry);
        if (cacheDataProviderResult) {
            store.put(dataProviderMethod, data);
        }
        return data;

    } catch (Exception e) {
        throw new ParameterResolutionException(
                String.format("Exception while invoking dataprovider method '%s': %s", dataProviderMethod.getName(),
                        e.getMessage()),
                e);
    }
}
项目:junit-dataprovider    文件:DataProviderParameterResolver.java   
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
        throws ParameterResolutionException {
    Object result = arguments.get(parameterContext.getIndex());

    // TODO workaround for https://github.com/junit-team/junit5/issues/1092
    Class<?> parameterType = parameterContext.getParameter().getType();
    if (parameterType.isPrimitive()) {
        return convertToBoxedTypeAsWorkaroundForNotWorkingWideningAndUnboxingConversion(result, parameterType);
    }

    return result;
}
项目:junit-dataprovider    文件:UseDataProviderInvocationContextProvider.java   
/**
 * Retrieves the test data from given dataprovider method.
 *
 * @param dataProviderMethod the dataprovider method that gives the parameters; never {@code null}
 * @param cacheDataProviderResult determines if the dataprovider result should be cached using
 *            {@code dataProviderMethod} as key
 * @param context the execution context to use to create a {@link TestInfo} if required; never {@code null}
 *
 * @return a list of methods, each method bound to a parameter combination returned by the dataprovider
 * @throws NullPointerException if and only if one of the given arguments is {@code null}
 */
protected Object invokeDataProviderMethodToRetrieveData(Method dataProviderMethod, boolean cacheDataProviderResult,
        ExtensionContext context) {
    checkNotNull(dataProviderMethod, "'dataProviderMethod' must not be null");
    checkNotNull(context, "'context' must not be null");

    Store store = context.getRoot().getStore(NAMESPACE_USE_DATAPROVIDER);

    Object cached = store.get(dataProviderMethod);
    if (cached != null) {
        return cached;
    }
    try {
        // TODO how to not require junit-jupiter-engine dependency and reuse already existing ExtensionRegistry?
        ExtensionRegistry extensionRegistry = createRegistryWithDefaultExtensions(emptyConfigurationParameters());
        Object data = executableInvoker.invoke(dataProviderMethod, context.getTestInstance().orElse(null), context,
                extensionRegistry);
        if (cacheDataProviderResult) {
            store.put(dataProviderMethod, data);
        }
        return data;

    } catch (Exception e) {
        throw new ParameterResolutionException(
                String.format("Exception while invoking dataprovider method '%s': %s", dataProviderMethod.getName(),
                        e.getMessage()),
                e);
    }
}
项目:mastering-junit5    文件:MyParameterResolver.java   
@Override
public boolean supportsParameter(ParameterContext parameterContext,
        ExtensionContext extensionContext)
        throws ParameterResolutionException {
    return true;
}
项目:mastering-junit5    文件:MyParameterResolver.java   
@Override
public Object resolveParameter(ParameterContext parameterContext,
        ExtensionContext extensionContext)
        throws ParameterResolutionException {
    return "my parameter";
}
项目:docker-compose-rule-with-junit5    文件:DockerComposeExtension.java   
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
    return parameterContext.getParameter().getType().equals(DockerComposeRule.class);
}
项目:docker-compose-rule-with-junit5    文件:DockerComposeExtension.java   
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
    return docker;
}
项目:open-kilda    文件:MockitoExtension.java   
@Override
public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
    return getMock(parameterContext.getParameter(), extensionContext);

}
项目:open-kilda    文件:MockitoExtension.java   
@Override
public boolean supports(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
    return parameterContext.getParameter().isAnnotationPresent(Mock.class);
}