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

The following examples show how to use org.junit.jupiter.api.extension.ExtensionContext#getStore() . 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: TestcontainersExtension.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Override
public void beforeAll(ExtensionContext context) {
    Class<?> testClass = context.getTestClass()
        .orElseThrow(() -> new ExtensionConfigurationException("TestcontainersExtension is only supported for classes."));

    Store store = context.getStore(NAMESPACE);
    List<StoreAdapter> sharedContainersStoreAdapters = findSharedContainers(testClass);

    sharedContainersStoreAdapters.forEach(adapter -> store.getOrComputeIfAbsent(adapter.getKey(), k -> adapter.start()));

    List<TestLifecycleAware> lifecycleAwareContainers = sharedContainersStoreAdapters
        .stream()
        .filter(this::isTestLifecycleAware)
        .map(lifecycleAwareAdapter -> (TestLifecycleAware) lifecycleAwareAdapter.container)
        .collect(toList());

    store.put(SHARED_LIFECYCLE_AWARE_CONTAINERS, lifecycleAwareContainers);
    signalBeforeTestToContainers(lifecycleAwareContainers, testDescriptionFrom(context));
}
 
Example 2
Source File: ComponentValidatorTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Override
public void afterEach(final ExtensionContext context) {
    final ExtensionContext.Store store = context.getStore(NAMESPACE);
    final boolean fails = !ComponentPackage.class.cast(store.get(ComponentPackage.class.getName())).success();
    final String expectedMessage = ExceptionSpec.class
            .cast(context.getStore(NAMESPACE).get(ExceptionSpec.class.getName()))
            .getMessage();
    try {
        ComponentValidator.class.cast(store.get(ComponentValidator.class.getName())).run();
        if (fails) {
            fail("should have failed");
        }
        if (expectedMessage != null) {
            final Collection<String> messages = TestLog.class.cast(store.get(TestLog.class.getName())).messages;
            assertTrue(messages.stream().anyMatch(it -> it.contains(expectedMessage)),
                    expectedMessage + "\n\n> " + messages);
        }
    } catch (final IllegalStateException ise) {
        if (fails) {
            final String exMsg = ise.getMessage();
            assertTrue(exMsg.contains(expectedMessage), expectedMessage + "\n\n> " + exMsg);
        } else {
            fail(ise);
        }
    }
}
 
Example 3
Source File: IdeaMocksExtension.java    From GitToolBox with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeEach(ExtensionContext context) {
  IdeaMocksImpl ideaMocks = new IdeaMocksImpl();
  Project project = mock(Project.class);
  MessageBus messageBus = mock(MessageBus.class);
  when(project.getMessageBus()).thenReturn(messageBus);
  when(messageBus.syncPublisher(any(Topic.class))).thenAnswer(invocation -> {
    Topic topic = invocation.getArgument(0);
    Class<?> listenerClass = topic.getListenerClass();
    if (ideaMocks.hasMockListener(listenerClass)) {
      return ideaMocks.getMockListener(listenerClass);
    } else {
      return ideaMocks.mockListener(listenerClass);
    }
  });
  Store store = context.getStore(NS);
  ParameterHolder holder = ParameterHolder.getHolder(store);
  holder.register(Project.class, Suppliers.ofInstance(project));
  holder.register(MessageBus.class, Suppliers.ofInstance(messageBus));
  holder.register(IdeaMocks.class, Suppliers.ofInstance(ideaMocks));
}
 
Example 4
Source File: GuiceExtension.java    From bobcat with Apache License 2.0 6 votes vote down vote up
/**
 * Create {@link Injector} or get existing one from test context
 */
private static Optional<Injector> getOrCreateInjector(ExtensionContext context)
    throws NoSuchMethodException, InstantiationException, IllegalAccessException,
    InvocationTargetException {

  Optional<AnnotatedElement> optionalAnnotatedElement = context.getElement();
  if (!optionalAnnotatedElement.isPresent()) {
    return Optional.empty();
  }

  AnnotatedElement element = optionalAnnotatedElement.get();
  Store store = context.getStore(NAMESPACE);

  Injector injector = store.get(element, Injector.class);
  if (injector == null) {
    injector = createInjector(context);
    store.put(element, injector);
  }

  return Optional.of(injector);
}
 
Example 5
Source File: MockitoExtension.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
private Object getMock(Parameter parameter, ExtensionContext extensionContext) {
    Class<?> mockType = parameter.getType();
    Store mocks = extensionContext.getStore(Namespace.create(MockitoExtension.class, mockType));
    String mockName = getMockName(parameter);

    if (mockName != null) {
        return mocks.getOrComputeIfAbsent(mockName, key -> mock(mockType, mockName));
    }
    else {
        return mocks.getOrComputeIfAbsent(mockType.getCanonicalName(), key -> mock(mockType));
    }
}
 
Example 6
Source File: MockitoExtension.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
private Object getMock(Parameter parameter, ExtensionContext extensionContext) {
    Class<?> mockType = parameter.getType();
    Store mocks = extensionContext.getStore(Namespace.create(MockitoExtension.class, mockType));
    String mockName = getMockName(parameter);

    if (mockName != null) {
        return mocks.getOrComputeIfAbsent(mockName, key -> mock(mockType, mockName));
    }
    else {
        return mocks.getOrComputeIfAbsent(mockType.getCanonicalName(), key -> mock(mockType));
    }
}
 
Example 7
Source File: Neo4jExtension.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeEach(ExtensionContext context) throws Exception {
	ExtensionContext.Store contextStore = context.getStore(NAMESPACE);
	Neo4jConnectionSupport neo4jConnectionSupport = contextStore
		.get(KEY_DRIVER_INSTANCE, Neo4jConnectionSupport.class);
	checkRequiredFeatures(neo4jConnectionSupport, context.getTags());
}
 
Example 8
Source File: MonoMeecrowaveExtension.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeAll(final ExtensionContext context) {
    final ExtensionContext.Store store = context.getStore(NAMESPACE);
    store.put(MonoBase.Instance.class, BASE.startIfNeeded());
    if (isPerClass(context)) {
        doInject(context);
        store.put(LifecyleState.class, onInjection(context, null));
    }
}
 
Example 9
Source File: VaultVersionExtension.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {

	Optional<RequiresVaultVersion> optional = AnnotationUtils.findAnnotation(context.getElement(),
			RequiresVaultVersion.class);

	if (!optional.isPresent()) {
		return ENABLED_BY_DEFAULT;
	}

	ExtensionContext.Store store = context.getStore(VAULT);

	Version runningVersion = store.getOrComputeIfAbsent(Version.class, versionClass -> {

		VaultInitializer initializer = new VaultInitializer();
		initializer.initialize();
		return initializer.prepare().getVersion();
	}, Version.class);

	RequiresVaultVersion requiredVersion = optional.get();

	Version required = Version.parse(requiredVersion.value());

	if (runningVersion.isGreaterThanOrEqualTo(required)) {
		return ConditionEvaluationResult
				.enabled(String.format("@VaultVersion check passed current Vault version is %s", runningVersion));
	}

	return ConditionEvaluationResult.disabled(String.format(
			"@VaultVersion requires since version %s, current Vault version is %s", required, runningVersion));
}
 
Example 10
Source File: AppExtension.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void afterAll(ExtensionContext context) throws Exception {
    ExtensionContext.Store store = context.getStore(ExtensionContext.Namespace.create(AppExtension.class, MockApp.class));
    MockApp app = (MockApp) store.get(MockApp.class);
    if (app != null) {
        app.stop();
        new TempDirectory(app.dir()).delete();
    }
}
 
Example 11
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 12
Source File: MonoMeecrowaveExtension.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeEach(final ExtensionContext context) {
    final ExtensionContext.Store store = context.getStore(NAMESPACE);
    if (!isPerClass(context)) {
        doInject(context);
        store.put(
            LifecyleState.class,
            onInjection(context.getParent().orElse(context), store.get(LifecyleState.class, LifecyleState.class)));
    }
}
 
Example 13
Source File: TimingExtension.java    From Mastering-Software-Testing-with-JUnit-5 with MIT License 4 votes vote down vote up
private Store getStore(ExtensionContext context) {
    return context.getStore(Namespace.create(getClass(), context));
}
 
Example 14
Source File: P4ServerExtension.java    From p4ic4idea with Apache License 2.0 4 votes vote down vote up
private ExtensionContext.Store getStore(ExtensionContext context) {
    return context.getStore(ExtensionContext.Namespace.create(getClass(), context.getRequiredTestMethod()));
}
 
Example 15
Source File: ErrorCollectorExtension.java    From p4ic4idea with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private Errors getErrors(ExtensionContext extensionContext) {
    ExtensionContext.Store store = extensionContext.getStore(ExtensionContext.Namespace.create(getClass(), extensionContext.getRequiredTestMethod()));
    return (Errors)store.getOrComputeIfAbsent("errors", (key) -> new Errors());
}
 
Example 16
Source File: TestcontainersExtension.java    From testcontainers-java with MIT License 4 votes vote down vote up
@Override
public void postProcessTestInstance(final Object testInstance, final ExtensionContext context) {
    Store store = context.getStore(NAMESPACE);
    store.put(TEST_INSTANCE, testInstance);
}
 
Example 17
Source File: IdeaLightweightExtension.java    From p4ic4idea with Apache License 2.0 4 votes vote down vote up
private ExtensionContext.Store getStore(ExtensionContext context) {
    return context.getStore(ExtensionContext.Namespace.create(getClass(), context.getRequiredTestMethod()));
}
 
Example 18
Source File: GuiceyExtensionsSupport.java    From dropwizard-guicey with MIT License 4 votes vote down vote up
private ExtensionContext.Store getLocalExtensionStore(final ExtensionContext context) {
    // test scoped extension scope (required to differentiate nested classes or parameterized executions)
    return context.getStore(ExtensionContext.Namespace
            .create(GuiceyExtensionsSupport.class, context.getRequiredTestClass()));
}
 
Example 19
Source File: ExtensionContextUtils.java    From weld-junit with Apache License 2.0 2 votes vote down vote up
/**
 * We use custom namespace based on this extension class and test class, cannot be stored as static variable as test class
 * name changes throughout testsuite execution
 *
 * @param context {@link ExtensionContext} you are currently using
 * @return {@link ExtensionContext.Store} based on {@link ExtensionContext} and the required test class
 */
private static ExtensionContext.Store getTestStore(ExtensionContext context) {
    return context.getStore(Namespace.create(WeldJunit5Extension.class, context.getRequiredTestClass()));
}
 
Example 20
Source File: CaptureSystemOutExtension.java    From junit-servers with MIT License 2 votes vote down vote up
/**
 * Get extension store.
 *
 * @param context The extension context.
 * @return The extension store.
 */
private static Store getStore(ExtensionContext context) {
	return context.getStore(NAMESPACE);
}