org.junit.jupiter.api.extension.ParameterResolutionException Java Examples

The following examples show how to use org.junit.jupiter.api.extension.ParameterResolutionException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FlowableExtension.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext context) {
    FlowableTestHelper flowableTestHelper = getTestHelper(context);
    if (parameterContext.isAnnotated(DeploymentId.class)) {
        return flowableTestHelper.getDeploymentIdFromDeploymentAnnotation();
    }

    Class<?> parameterType = parameterContext.getParameter().getType();
    ProcessEngine processEngine = flowableTestHelper.getProcessEngine();
    if (parameterType.isInstance(processEngine)) {
        return processEngine;
    } else if (FlowableTestHelper.class.equals(parameterType)) {
        return flowableTestHelper;
    } else if (FlowableMockSupport.class.equals(parameterType)) {
        return flowableTestHelper.getMockSupport();
    }

    try {
        return ProcessEngine.class.getDeclaredMethod("get" + parameterType.getSimpleName()).invoke(processEngine);
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
        throw new ParameterResolutionException("Could not find service " + parameterType, ex);
    }
}
 
Example #2
Source File: MockitoExtension.java    From junit5-extensions with MIT License 6 votes vote down vote up
@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());
}
 
Example #3
Source File: HibernateSessionExtension.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
        throws ParameterResolutionException {

    Configuration config = new Configuration();

    Class<?> declaringClass = parameterContext.getDeclaringExecutable().getDeclaringClass();
    WithHibernateSession annotation = getAnnotation(declaringClass);
    for (Class<?> modelClass : annotation.models()) {
        config.addAnnotatedClass(modelClass);
    }

    config.setProperty(DIALECT, H2Dialect.class.getName());
    config.setProperty(DRIVER, Driver.class.getName());
    config.setProperty(URL, "jdbc:h2:mem:./" + UUID.randomUUID().toString());
    config.setProperty(HBM2DDL_AUTO, "create");
    config.setProperty(CURRENT_SESSION_CONTEXT_CLASS, "managed");
    config.setProperty(GENERATE_STATISTICS, "false");

    SessionFactory sessionFactory = config.buildSessionFactory();
    openSession(sessionFactory, extensionContext);
    return sessionFactory;
}
 
Example #4
Source File: QuarkusTestExtension.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * We don't actually have to resolve the parameter (thus the default values in the implementation)
 * since the class instance that is passed to JUnit isn't really used.
 * The actual test instance that is used is the one that is pulled from Arc, which of course will already have its
 * constructor parameters properly resolved
 */
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
        throws ParameterResolutionException {
    String className = parameterContext.getParameter().getType().getName();
    switch (className) {
        case "boolean":
            return false;
        case "byte":
        case "short":
        case "int":
            return 0;
        case "long":
            return 0L;
        case "float":
            return 0.0f;
        case "double":
            return 0.0d;
        case "char":
            return '\u0000';
        default:
            return null;
    }
}
 
Example #5
Source File: JigTestExtension.java    From jig with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
    if (parameterContext.getParameter().getType() == Configuration.class) return configuration;
    if (parameterContext.getParameter().getType() == Sources.class) return getTestRawSource();

    for (Field field : Configuration.class.getDeclaredFields()) {
        if (field.getType() == parameterContext.getParameter().getType()) {
            try {
                field.setAccessible(true);
                return field.get(configuration);
            } catch (IllegalAccessException e) {
                throw new AssertionError(e);
            }
        }
    }

    // 実装ミスでもなければここには来ない
    throw new AssertionError();
}
 
Example #6
Source File: FlowableCmmnExtension.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext context) {
    FlowableCmmnTestHelper flowableTestHelper = getTestHelper(context);
    if (parameterContext.isAnnotated(CmmnDeploymentId.class)) {
        return flowableTestHelper.getDeploymentIdFromDeploymentAnnotation();
    }

    Class<?> parameterType = parameterContext.getParameter().getType();
    CmmnEngine cmmnEngine = flowableTestHelper.getCmmnEngine();
    if (parameterType.isInstance(cmmnEngine)) {
        return cmmnEngine;
    } else if (FlowableCmmnTestHelper.class.equals(parameterType)) {
        return flowableTestHelper;
    }

    try {
        return CmmnEngine.class.getDeclaredMethod("get" + parameterType.getSimpleName()).invoke(cmmnEngine);
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
        throw new ParameterResolutionException("Could not find service " + parameterType, ex);
    }
}
 
Example #7
Source File: RedisServerExtension.java    From cava with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
    throws ParameterResolutionException {
  if (redisServer == null) {
    String localhost = InetAddress.getLoopbackAddress().getHostAddress();

    redisServer = RedisServer
        .builder()
        .setting("bind " + localhost)
        .setting("maxmemory 128mb")
        .setting("maxmemory-policy allkeys-lru")
        .setting("appendonly no")
        .setting("save \"\"")
        .port(findFreePort())
        .build();
    Runtime.getRuntime().addShutdownHook(shutdownThread);
    redisServer.start();
  }
  return redisServer.ports().get(0);
}
 
Example #8
Source File: TestKitExtension.java    From exonum-java-binding with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveParameter(
    ParameterContext parameterContext, ExtensionContext extensionContext)
    throws ParameterResolutionException {
  checkExtensionContext(extensionContext);
  CloseableTestKit closeableTestKit =
      getStore(extensionContext).get(TESTKIT_KEY, CloseableTestKit.class);
  TestKit testKit;
  if (closeableTestKit == null) {
    testKit = buildTestKit(parameterContext, extensionContext);
    getStore(extensionContext).put(TESTKIT_KEY, new CloseableTestKit(testKit));
  } else {
    // Throw an exception if TestKit was already instantiated in this context, but user tries to
    // reconfigure it
    if (annotationsUsed(parameterContext)) {
      throw new ParameterResolutionException("TestKit was parameterized with annotations after"
          + " being instantiated in " + extensionContext.getDisplayName());
    }
    testKit = closeableTestKit.getTestKit();
  }
  return testKit;
}
 
Example #9
Source File: FlowableDmnExtension.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext context) {
    FlowableDmnTestHelper flowableTestHelper = getTestHelper(context);
    if (parameterContext.isAnnotated(DmnDeploymentId.class)) {
        return flowableTestHelper.getDeploymentIdFromDeploymentAnnotation();
    }

    Class<?> parameterType = parameterContext.getParameter().getType();
    DmnEngine dmnEngine = flowableTestHelper.getDmnEngine();
    if (parameterType.isInstance(dmnEngine)) {
        return dmnEngine;
    } else if (FlowableDmnTestHelper.class.equals(parameterType)) {
        return flowableTestHelper;
    }

    try {
        return DmnEngine.class.getDeclaredMethod("get" + parameterType.getSimpleName()).invoke(dmnEngine);
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
        throw new ParameterResolutionException("Could not find service " + parameterType, ex);
    }
}
 
Example #10
Source File: ParametrizedTestCompatibilityTest.java    From junit5-extensions with MIT License 5 votes vote down vote up
@ExpectFailure(
        @Cause(
                type = ParameterResolutionException.class,
                message = "Discovered multiple competing ParameterResolvers"
        )
)
@IncludeModule(TestModule.class)
@ParameterizedTest
@ValueSource(strings = "valueSourceString")
void explicitBindingStringShouldConflictWithValueSource4(@Named("named") String value) {
}
 
Example #11
Source File: TempDirectoryExtension.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
    throws ParameterResolutionException {
  if (tempDirectory == null) {
    try {
      tempDirectory = createTempDirectory(extensionContext.getRequiredTestClass().getSimpleName());
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  }
  return tempDirectory;
}
 
Example #12
Source File: BrokerPropertiesParameterResolver.java    From spring-cloud-app-broker with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("PMD.AvoidUncheckedExceptionsInSignatures")
@Override
public BrokerProperties resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
	throws ParameterResolutionException {
	String[] properties = getValueHolderProperties(extensionContext);
	return new BrokerProperties(properties);
}
 
Example #13
Source File: ParametrizedTestCompatibilityTest.java    From junit5-extensions with MIT License 5 votes vote down vote up
@ExpectFailure(
        @Cause(
                type = ParameterResolutionException.class,
                message = "Discovered multiple competing ParameterResolvers"
        )
)
@IncludeModule(TestModule.class)
@ParameterizedTest
@ValueSource(strings = "valueSourceString")
void explicitBindingStringShouldConflictWithValueSource(String value) {
}
 
Example #14
Source File: TestKitExtension.java    From exonum-java-binding with Apache License 2.0 5 votes vote down vote up
/**
 * Check the extension context and throw if TestKit is injected in @BeforeAll or @AfterAll.
 */
private void checkExtensionContext(ExtensionContext extensionContext) {
  Optional<Method> testMethod = extensionContext.getTestMethod();
  if (testMethod.isEmpty()) {
    throw new ParameterResolutionException("TestKit can't be injected in @BeforeAll or @AfterAll"
        + " because it is a stateful, mutable object and sharing it between all tests is"
        + " error-prone. Consider injecting it in @BeforeEach instead.\n"
        + " If you do need the same instance for all tests — just use `TestKit#builder`"
        + " directly. Don't forget to destroy it in @AfterEach.");
  }
}
 
Example #15
Source File: VertxExtension.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
    throws ParameterResolutionException {
  if (vertx == null) {
    System.setProperty("vertx.disableFileCPResolving", "true");
    vertx = Vertx.vertx();
  }
  return vertx;
}
 
Example #16
Source File: ParametrizedTestCompatibilityTest.java    From junit5-extensions with MIT License 5 votes vote down vote up
@ExpectFailure(
        @Cause(
                type = ParameterResolutionException.class,
                message = "Discovered multiple competing ParameterResolvers"
        )
)
@IncludeModule(TestModule.class)
@ParameterizedTest
@ValueSource(strings = "valueSourceString")
void explicitBindingStringShouldConflictWithValueSource2(@SomeBindingAnnotation String value) {
}
 
Example #17
Source File: GuiceExtensionTest.java    From junit5-extensions with MIT License 5 votes vote down vote up
@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) {}
 
Example #18
Source File: ParametrizedTestCompatibilityTest.java    From junit5-extensions with MIT License 5 votes vote down vote up
@ExpectFailure(
        @Cause(
                type = ParameterResolutionException.class,
                message = "Discovered multiple competing ParameterResolvers"
        )
)
@IncludeModule(TestModule.class)
@ParameterizedTest
@ValueSource(strings = "valueSourceString")
void explicitBindingStringShouldConflictWithValueSource3(@SomeQualifyingAnnotation String value) {
}
 
Example #19
Source File: JigTestExtension.java    From jig with Apache License 2.0 5 votes vote down vote up
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
    if (parameterContext.getParameter().getType() == Configuration.class) return true;
    if (parameterContext.getParameter().getType() == Sources.class) return true;
    if (parameterContext.getParameter().getType() == AnalyzedImplementation.class) return true;
    for (Field field : Configuration.class.getDeclaredFields()) {
        if (field.getType() == parameterContext.getParameter().getType()) {
            return true;
        }
    }
    return false;
}
 
Example #20
Source File: GuiceExtensionTest.java    From junit5-extensions with MIT License 5 votes vote down vote up
@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) {}
 
Example #21
Source File: RootElementResolver.java    From JUnit-5-Quick-Start-Guide-and-Framework-Support with MIT License 5 votes vote down vote up
@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;
    }
}
 
Example #22
Source File: UsageExampleTests.java    From junit5-extensions with MIT License 5 votes vote down vote up
@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) {}
 
Example #23
Source File: MockWebServiceExtension.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
    Class<?> parameterType = parameterContext.getParameter().getType();
    if (WebServiceMock.class.equals(parameterType)) {
        return getMockWebServiceContext(extensionContext).webServiceMock;
    } else if (Server.class.equals(parameterType)) {
        return getMockWebServiceContext(extensionContext).server;
    }
    throw new ParameterResolutionException("Cannot resolve parameter for parameter context: " + parameterContext);
}
 
Example #24
Source File: RandomIntegerResolver.java    From demo-junit-5 with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
@Override
public boolean supportsParameter(
		ParameterContext parameterContext, ExtensionContext extensionContext)
		throws ParameterResolutionException {
	// don't blindly support a common type like `Integer`
	// instead it should be annotated with `@Randomized` or something
	Class<?> targetType = parameterContext.getParameter().getType();
	return targetType == Integer.class || targetType == int.class;
}
 
Example #25
Source File: UsageExampleTests.java    From junit5-extensions with MIT License 5 votes vote down vote up
@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) {}
 
Example #26
Source File: WeldJunit5Extension.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #27
Source File: WeldJunit5Extension.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example #28
Source File: UsageExampleTests.java    From junit5-extensions with MIT License 5 votes vote down vote up
@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) {}
 
Example #29
Source File: UsageExampleTests.java    From junit5-extensions with MIT License 5 votes vote down vote up
@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) {}
 
Example #30
Source File: UsageExampleTests.java    From junit5-extensions with MIT License 5 votes vote down vote up
@ExpectFailure({
    @Cause(type = ParameterResolutionException.class),
    @Cause(type = ArgumentConversionException.class),
    @Cause(type = ClassNotFoundException.class)
})
@ParameterizedTest
@ValueSource(strings = "123ClassDoesNotExist")
void classNotFound(@ConvertWith(ClassArgumentConverter.class) Class<?> clazz) {}