Java Code Examples for org.junit.jupiter.api.extension.ExtensionContext#getRequiredTestClass()

The following examples show how to use org.junit.jupiter.api.extension.ExtensionContext#getRequiredTestClass() . 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: MicroShedTestExtension.java    From microshed-testing with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeAll(ExtensionContext context) throws Exception {
    Class<?> testClass = context.getRequiredTestClass();

    // Explicitly trigger static initialization of any SharedContainerConfig before we do further processing
    if (testClass.isAnnotationPresent(SharedContainerConfig.class)) {
        Class.forName(testClass.getAnnotation(SharedContainerConfig.class).value().getName());
    }

    ApplicationEnvironment config = ApplicationEnvironment.Resolver.load();
    LOG.info("Using ApplicationEnvironment class: " + config.getClass().getCanonicalName());
    config.applyConfiguration(testClass);
    config.start();
    configureRestAssured(config);
    injectRestClients(testClass);
    injectKafkaClients(testClass);
}
 
Example 2
Source File: JUnit5InjectionSupport.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Override
default void postProcessTestInstance(final Object testInstance, final ExtensionContext context) {
    Class<?> testClass = context.getRequiredTestClass();
    while (testClass != Object.class) {
        Stream
                .of(testClass.getDeclaredFields())
                .filter(c -> c.isAnnotationPresent(injectionMarker()))
                .forEach(f -> {
                    if (!supports(f.getType())) {
                        throw new IllegalArgumentException("@" + injectionMarker() + " not supported on " + f);
                    }
                    if (!f.isAccessible()) {
                        f.setAccessible(true);
                    }
                    try {
                        f.set(testInstance, findInstance(context, f.getType(), f.getAnnotation(injectionMarker())));
                    } catch (final IllegalAccessException e) {
                        throw new IllegalStateException(e);
                    }
                });
        testClass = testClass.getSuperclass();
    }
}
 
Example 3
Source File: ResourceSetGlobalCompilationExtension.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeAll(ExtensionContext context) throws Exception {
	try {
		Class<?> type = context.getRequiredTestClass();
		if (!Modifier.isStatic(type.getModifiers())) {
			if (type.isMemberClass()) {
				throw new IllegalStateException("Member class annoted with MassiveCompilationExtension extension must be declared with static modifier.");
			}
		}
		injectMembers(this, context);
		clearCompilationContext(context);
	} catch (Throwable e) {
		e.printStackTrace();
	    Throwables.throwIfUnchecked(e);
	    throw new RuntimeException(e);
	}
}
 
Example 4
Source File: MicroProfileTestExtension.java    From microprofile-sandbox with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeAll(ExtensionContext context) throws Exception {
    Class<?> testClass = context.getRequiredTestClass();
    // For now this is hard-coded to using Testcontainers for container management.
    // In the future, this could be configurable to something besides Testcontainers
    TestcontainersConfiguration config = new TestcontainersConfiguration(testClass);
    config.applyConfiguration();
    config.startContainers();
    injectRestClients(testClass, config);
}
 
Example 5
Source File: SpringExtension.java    From spring-test-junit5 with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve a value for the {@link Parameter} in the supplied {@link ParameterContext} by
 * retrieving the corresponding dependency from the test's {@link ApplicationContext}.
 * <p>Delegates to {@link ParameterAutowireUtils#resolveDependency}.
 * @see #supportsParameter
 * @see ParameterAutowireUtils#resolveDependency
 */
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
	Parameter parameter = parameterContext.getParameter();
	Class<?> testClass = extensionContext.getRequiredTestClass();
	ApplicationContext applicationContext = getApplicationContext(extensionContext);
	return ParameterAutowireUtils.resolveDependency(parameter, testClass, applicationContext);
}
 
Example 6
Source File: IntegrationExtension.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessTestInstance(Object testInstance, ExtensionContext context) {
    ExtensionContext.Store store = context.getRoot().getStore(ExtensionContext.Namespace.GLOBAL);
    Class<?> testClass = context.getRequiredTestClass();
    AbstractTestModule module = store.getOrComputeIfAbsent(AbstractTestModule.class, key -> createTestModule(testClass, store), AbstractTestModule.class);
    module.inject(testInstance);
}
 
Example 7
Source File: BQTestExtension.java    From bootique with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeAll(ExtensionContext context) {
    ExtensionContext.Store store = context.getStore(NAMESPACE);
    Class<?> testType = context.getRequiredTestClass();
    ReflectionUtils
            .findFields(testType, isRunnable(), ReflectionUtils.HierarchyTraversalMode.TOP_DOWN)
            .stream()
            .map(f -> getInstance(null, f))
            .forEach(r -> startAndRegisterForShutdown(r, store));
}
 
Example 8
Source File: TestUtils.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public static Path getLogsPath(ExtensionContext extensionContext, String rootFolder) {
    String testMethod = extensionContext.getDisplayName();
    Class<?> testClass = extensionContext.getRequiredTestClass();
    Path path = Environment.getInstance().testLogDir().resolve(Paths.get(rootFolder, testClass.getName()));
    if (testMethod != null) {
        path = path.resolve(testMethod);
    }
    return path;
}
 
Example 9
Source File: PluggableFlowableExtension.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
protected ProcessEngine getProcessEngine(ExtensionContext context) {
    ProcessEngine processEngine = getStore(context).getOrComputeIfAbsent(PROCESS_ENGINE, key -> initializeProcessEngine(), ProcessEngine.class);

    // Enable verbose execution tree debugging if needed
    Class<?> testClass = context.getRequiredTestClass();
    if (AnnotationSupport.isAnnotated(testClass, EnableVerboseExecutionTreeLogging.class)) {
        swapCommandInvoker(processEngine, true);
    }
    return processEngine;
}
 
Example 10
Source File: QuarkusTestExtension.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T interceptTestClassConstructor(Invocation<T> invocation,
        ReflectiveInvocationContext<Constructor<T>> invocationContext, ExtensionContext extensionContext) throws Throwable {
    if (isNativeTest(extensionContext)) {
        return invocation.proceed();
    }
    T result;
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    Class<?> requiredTestClass = extensionContext.getRequiredTestClass();
    try {
        Thread.currentThread().setContextClassLoader(requiredTestClass.getClassLoader());
        result = invocation.proceed();
    } catch (NullPointerException e) {
        throw new RuntimeException(
                "When using constructor injection in a test, the only legal operation is to assign the constructor values to fields. Offending class is "
                        + requiredTestClass,
                e);
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
    ExtensionState state = ensureStarted(extensionContext);
    if (failedBoot) {
        return result;
    }

    // We do this here as well, because when @TestInstance(Lifecycle.PER_CLASS) is used on a class,
    // interceptTestClassConstructor is called before beforeAll, meaning that the TCCL will not be set correctly
    // (for any test other than the first) unless this is done
    old = null;
    if (runningQuarkusApplication != null) {
        old = setCCL(runningQuarkusApplication.getClassLoader());
    }

    initTestState(extensionContext, state);
    if (old != null) {
        setCCL(old);
    }
    return result;
}
 
Example 11
Source File: SpringExtension.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Get the {@link TestContextManager} associated with the supplied {@code ExtensionContext}.
 * @return the {@code TestContextManager} (never {@code null})
 */
private static TestContextManager getTestContextManager(ExtensionContext context) {
	Assert.notNull(context, "ExtensionContext must not be null");
	Class<?> testClass = context.getRequiredTestClass();
	Store store = getStore(context);
	return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class);
}
 
Example 12
Source File: SpringExtension.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Resolve a value for the {@link Parameter} in the supplied {@link ParameterContext} by
 * retrieving the corresponding dependency from the test's {@link ApplicationContext}.
 * <p>Delegates to {@link ParameterAutowireUtils#resolveDependency}.
 * @see #supportsParameter
 * @see ParameterAutowireUtils#resolveDependency
 */
@Override
@Nullable
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
	Parameter parameter = parameterContext.getParameter();
	int index = parameterContext.getIndex();
	Class<?> testClass = extensionContext.getRequiredTestClass();
	ApplicationContext applicationContext = getApplicationContext(extensionContext);
	return ParameterAutowireUtils.resolveDependency(parameter, index, testClass, applicationContext);
}
 
Example 13
Source File: SpringExtension.java    From spring-test-junit5 with Apache License 2.0 5 votes vote down vote up
/**
 * Get the {@link TestContextManager} associated with the supplied {@code ExtensionContext}.
 * @return the {@code TestContextManager} (never {@code null})
 */
private static TestContextManager getTestContextManager(ExtensionContext context) {
	Assert.notNull(context, "ExtensionContext must not be null");
	Class<?> testClass = context.getRequiredTestClass();
	Store store = getStore(context);
	return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class);
}
 
Example 14
Source File: SpringExtension.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Get the {@link TestContextManager} associated with the supplied {@code ExtensionContext}.
 * @return the {@code TestContextManager} (never {@code null})
 */
private static TestContextManager getTestContextManager(ExtensionContext context) {
	Assert.notNull(context, "ExtensionContext must not be null");
	Class<?> testClass = context.getRequiredTestClass();
	Store store = getStore(context);
	return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class);
}
 
Example 15
Source File: CassandraClusterExtension.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public void afterAll(ExtensionContext extensionContext) {
    Class<?> testClass = extensionContext.getRequiredTestClass();
    if (testClass.getEnclosingClass() == null) {
        cassandraCluster.close();
        cassandraExtension.afterAll(extensionContext);
    }
}
 
Example 16
Source File: QuarkusDevModeTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeEach(ExtensionContext extensionContext) throws Exception {
    if (archiveProducer == null) {
        throw new RuntimeException("QuarkusDevModeTest does not have archive producer set");
    }

    if (logFileName != null) {
        PropertyTestUtil.setLogFileProperty(logFileName);
    } else {
        PropertyTestUtil.setLogFileProperty();
    }
    ExtensionContext.Store store = extensionContext.getRoot().getStore(ExtensionContext.Namespace.GLOBAL);
    if (store.get(TestResourceManager.class.getName()) == null) {
        TestResourceManager manager = new TestResourceManager(extensionContext.getRequiredTestClass());
        manager.init();
        manager.start();
        store.put(TestResourceManager.class.getName(), new ExtensionContext.Store.CloseableResource() {

            @Override
            public void close() throws Throwable {
                manager.close();
            }
        });
    }

    Class<?> testClass = extensionContext.getRequiredTestClass();
    try {
        deploymentDir = Files.createTempDirectory("quarkus-dev-mode-test");
        testLocation = PathTestHelper.getTestClassesLocation(testClass);

        //TODO: this is a huge hack, at the moment this just guesses the source location
        //this can be improved, but as this is for testing extensions it is probably fine for now
        String sourcePath = System.getProperty("quarkus.test.source-path");
        ;
        if (sourcePath == null) {
            //TODO: massive hack, make sure this works in eclipse
            projectSourceRoot = testLocation.getParent().getParent().resolve("src/test/java");
        } else {
            projectSourceRoot = Paths.get(sourcePath);
        }

        DevModeContext context = exportArchive(deploymentDir, projectSourceRoot);
        context.setArgs(commandLineArgs);
        context.setTest(true);
        context.setAbortOnFailedStart(true);
        context.getBuildSystemProperties().put("quarkus.banner.enabled", "false");
        devModeMain = new DevModeMain(context);
        devModeMain.start();
        ApplicationStateNotification.waitForApplicationStart();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 17
Source File: JsonFileArgumentsProvider.java    From junit-json-params with Apache License 2.0 4 votes vote down vote up
private InputStream openInputStream(ExtensionContext context, String resource) {
    Class<?> testClass = context.getRequiredTestClass();
    InputStream inputStream = inputStreamProvider.apply(testClass, resource);
    return Preconditions.notNull(inputStream,
            () -> "Classpath resource does not exist: " + resource);
}
 
Example 18
Source File: SnapshotAssertions.java    From curiostack with MIT License 4 votes vote down vote up
private static Class<?> getTopLevelClass(ExtensionContext ctx) {
  while (ctx.getParent().isPresent() && ctx.getParent().get().getTestClass().isPresent()) {
    ctx = ctx.getParent().get();
  }
  return ctx.getRequiredTestClass();
}
 
Example 19
Source File: IgnorableTestExtension.java    From sarl with Apache License 2.0 4 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
	// This test is working only in Eclipse, or Maven/Tycho.
	TestScope scope = context.getRequiredTestClass().getAnnotation(TestScope.class);
	if (scope == null) {
		Class<?> enclosingType = context.getRequiredTestClass();
		while (scope == null && enclosingType != null) {
			scope = enclosingType.getAnnotation(TestScope.class);
			enclosingType = enclosingType.getEnclosingClass();
		}
	}
	if (scope != null) {
		if (!scope.tycho() && !scope.eclipse()) {
			return ConditionEvaluationResult.disabled("not running on the current framework");
		}
		if (scope.tycho() || scope.eclipse()) {
			boolean isEclipse = TestUtils.isEclipseRuntimeEnvironment();
			if (scope.tycho()) {
				if (isEclipse) {
					return ConditionEvaluationResult.disabled("cannot run Tycho-specific test in Eclipse");
				}
			} else if (!isEclipse) {
				return ConditionEvaluationResult.disabled("cannot run Eclipse-specific test outside Eclipse");
			}
		}
		if (scope.needmavencentral()) {
			boolean canAccessNetwork = true;
			try {
				URL central = new URL(MAVEN_CENTRAL_REPOSITORY_URL);
				URLConnection connection = central.openConnection();
				connection.setConnectTimeout(MAVEN_CENTRAL_TIMEOUT);
				try (InputStream is = connection.getInputStream()) {
					byte[] buffer = new byte[128];
					int length = is.read(buffer);
					while (length > 0) {
						length = is.read(buffer);
					}
				}
			} catch (Exception exception) {
				canAccessNetwork = false;
			}
			if (!canAccessNetwork) {
				return ConditionEvaluationResult.disabled("cannot have access to Maven central server");
			}
		}
	}
	//
	if (isIgnorable(context)) {
		return ConditionEvaluationResult.disabled("this test is dynamically ignored.");
	}
	//
	return ConditionEvaluationResult.enabled("no dynamic condition for disabling this test");
}
 
Example 20
Source File: JunitServerExtension.java    From junit-servers with MIT License 3 votes vote down vote up
/**
 * Start and register the embedded server.
 *
 * The embedded server may be used in two modes:
 *
 * <ul>
 *   <li>Started before all tests, and stopped after all tests, this is the static mode (the extension has been used as a static extension).</li>
 *   <li>Started before each tests, and stopped after eacg tests, this is the non static mode (the extension has not been used as a static extension).</li>
 * </ul>
 *
 * @param context The test context.
 * @param staticMode {@code true} if the extension has been registered as a static extension, {@code false} otherwise.
 * @return The registered adapter.
 */
private EmbeddedServerRunner registerEmbeddedServer(ExtensionContext context, boolean staticMode) {
	log.debug("Register embedded server to junit extension context");

	Class<?> testClass = context.getRequiredTestClass();
	EmbeddedServer<?> server = this.server == null ? instantiateServer(testClass, configuration) : this.server;

	EmbeddedServerRunner serverAdapter = new EmbeddedServerRunner(server);
	serverAdapter.beforeAll();

	putEmbeddedServerAdapterInStore(context, serverAdapter, staticMode);

	return serverAdapter;
}