Java Code Examples for org.springframework.test.context.ContextCustomizer

The following examples show how to use org.springframework.test.context.ContextCustomizer. These examples are extracted from open source projects. 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
@Override
@Nullable
public ContextCustomizer createContextCustomizer(Class<?> testClass,
		List<ContextConfigurationAttributes> configAttributes) {

	if (webSocketPresent && isAnnotatedWithWebAppConfiguration(testClass)) {
		try {
			Class<?> clazz = ClassUtils.forName(MOCK_SERVER_CONTAINER_CONTEXT_CUSTOMIZER_CLASS_NAME,
					getClass().getClassLoader());
			return (ContextCustomizer) BeanUtils.instantiateClass(clazz);
		}
		catch (Throwable ex) {
			throw new IllegalStateException("Failed to enable WebSocket test support; could not load class: " +
					MOCK_SERVER_CONTAINER_CONTEXT_CUSTOMIZER_CLASS_NAME, ex);
		}
	}

	// Else, nothing to customize
	return null;
}
 
Example 2
@Override
@Nullable
public ContextCustomizer createContextCustomizer(Class<?> testClass,
		List<ContextConfigurationAttributes> configAttributes) {

	if (webSocketPresent && isAnnotatedWithWebAppConfiguration(testClass)) {
		try {
			Class<?> clazz = ClassUtils.forName(MOCK_SERVER_CONTAINER_CONTEXT_CUSTOMIZER_CLASS_NAME,
					getClass().getClassLoader());
			return (ContextCustomizer) BeanUtils.instantiateClass(clazz);
		}
		catch (Throwable ex) {
			throw new IllegalStateException("Failed to enable WebSocket test support; could not load class: " +
					MOCK_SERVER_CONTAINER_CONTEXT_CUSTOMIZER_CLASS_NAME, ex);
		}
	}

	// Else, nothing to customize
	return null;
}
 
Example 3
@Override
public ContextCustomizer createContextCustomizer(Class<?> testClass, List<ContextConfigurationAttributes> configAttributes) {
    Set<AutoConfigureEmbeddedDatabase> databaseAnnotations = AnnotatedElementUtils.getMergedRepeatableAnnotations(
            testClass, AutoConfigureEmbeddedDatabase.class, AutoConfigureEmbeddedDatabases.class);

    databaseAnnotations = databaseAnnotations.stream()
            .filter(distinctByKey(AutoConfigureEmbeddedDatabase::beanName))
            .filter(databaseAnnotation -> databaseAnnotation.type() == EmbeddedDatabaseType.POSTGRES)
            .filter(databaseAnnotation -> databaseAnnotation.replace() != Replace.NONE)
            .collect(Collectors.toCollection(LinkedHashSet::new));

    if (!databaseAnnotations.isEmpty()) {
        return new PreloadableEmbeddedPostgresContextCustomizer(databaseAnnotations);
    }

    return null;
}
 
Example 4
private Set<ContextCustomizer> getContextCustomizers(Class<?> testClass,
		List<ContextConfigurationAttributes> configAttributes) {

	List<ContextCustomizerFactory> factories = getContextCustomizerFactories();
	Set<ContextCustomizer> customizers = new LinkedHashSet<>(factories.size());
	for (ContextCustomizerFactory factory : factories) {
		ContextCustomizer customizer = factory.createContextCustomizer(testClass, configAttributes);
		if (customizer != null) {
			customizers.add(customizer);
		}
	}
	return customizers;
}
 
Example 5
@Override
protected List<ContextCustomizerFactory> getContextCustomizerFactories() {
	return singletonList(
		(ContextCustomizerFactory) (testClass, configAttributes) ->
			(ContextCustomizer) (context, mergedConfig) -> context.getBeanFactory().registerSingleton("foo", "foo")
	);
}
 
Example 6
private Set<ContextCustomizer> getContextCustomizers(Class<?> testClass,
		List<ContextConfigurationAttributes> configAttributes) {

	List<ContextCustomizerFactory> factories = getContextCustomizerFactories();
	Set<ContextCustomizer> customizers = new LinkedHashSet<>(factories.size());
	for (ContextCustomizerFactory factory : factories) {
		ContextCustomizer customizer = factory.createContextCustomizer(testClass, configAttributes);
		if (customizer != null) {
			customizers.add(customizer);
		}
	}
	return customizers;
}
 
Example 7
@Override
protected List<ContextCustomizerFactory> getContextCustomizerFactories() {
	return singletonList(
		(ContextCustomizerFactory) (testClass, configAttributes) ->
			(ContextCustomizer) (context, mergedConfig) -> context.getBeanFactory().registerSingleton("foo", "foo")
	);
}
 
Example 8
@Override
public ContextCustomizer createContextCustomizer(Class<?> testClass,
    List<ContextConfigurationAttributes> configAttributes) {

    if (isEmbeddedSpringBootTest(testClass)) {
        return new VertxWebTestClientContextCustomizer();
    }

    return null;
}
 
Example 9
@Test
public void shouldCreateCustomizer() {
    ContextCustomizer customizer = factory.createContextCustomizer(EmbeddedServerTestClass.class, null);

    assertThat(customizer).isNotNull();
    assertThat(customizer).isInstanceOf(VertxWebTestClientContextCustomizer.class);
}
 
Example 10
@Override
@Nullable
public ContextCustomizer createContextCustomizer(Class<?> testClass,
		List<ContextConfigurationAttributes> configAttributes) {
	EmbeddedCassandra annotation = AnnotatedElementUtils.findMergedAnnotation(testClass, EmbeddedCassandra.class);
	if (annotation != null) {
		return new EmbeddedCassandraContextCustomizer(annotation);
	}
	return null;
}
 
Example 11
Source Project: moduliths   Source File: ModuleContextCustomizerFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ContextCustomizer createContextCustomizer(Class<?> testClass,
		List<ContextConfigurationAttributes> configAttributes) {

	ModuleTest moduleTest = AnnotatedElementUtils.getMergedAnnotation(testClass, ModuleTest.class);

	return moduleTest == null ? null : new ModuleContextCustomizer(testClass);
}
 
Example 12
/**
 * Build the {@link MergedContextConfiguration merged context configuration}
 * for the supplied {@link Class testClass}, context configuration attributes,
 * and parent context configuration.
 * @param testClass the test class for which the {@code MergedContextConfiguration}
 * should be built (must not be {@code null})
 * @param configAttributesList the list of context configuration attributes for the
 * specified test class, ordered <em>bottom-up</em> (i.e., as if we were
 * traversing up the class hierarchy); never {@code null} or empty
 * @param parentConfig the merged context configuration for the parent application
 * context in a context hierarchy, or {@code null} if there is no parent
 * @param cacheAwareContextLoaderDelegate the cache-aware context loader delegate to
 * be passed to the {@code MergedContextConfiguration} constructor
 * @param requireLocationsClassesOrInitializers whether locations, classes, or
 * initializers are required; typically {@code true} but may be set to {@code false}
 * if the configured loader supports empty configuration
 * @return the merged context configuration
 * @see #resolveContextLoader
 * @see ContextLoaderUtils#resolveContextConfigurationAttributes
 * @see SmartContextLoader#processContextConfiguration
 * @see ContextLoader#processLocations
 * @see ActiveProfilesUtils#resolveActiveProfiles
 * @see ApplicationContextInitializerUtils#resolveInitializerClasses
 * @see MergedContextConfiguration
 */
private MergedContextConfiguration buildMergedContextConfiguration(Class<?> testClass,
		List<ContextConfigurationAttributes> configAttributesList, @Nullable MergedContextConfiguration parentConfig,
		CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate,
		boolean requireLocationsClassesOrInitializers) {

	Assert.notEmpty(configAttributesList, "ContextConfigurationAttributes list must not be null or empty");

	ContextLoader contextLoader = resolveContextLoader(testClass, configAttributesList);
	List<String> locations = new ArrayList<>();
	List<Class<?>> classes = new ArrayList<>();
	List<Class<?>> initializers = new ArrayList<>();

	for (ContextConfigurationAttributes configAttributes : configAttributesList) {
		if (logger.isTraceEnabled()) {
			logger.trace(String.format("Processing locations and classes for context configuration attributes %s",
					configAttributes));
		}
		if (contextLoader instanceof SmartContextLoader) {
			SmartContextLoader smartContextLoader = (SmartContextLoader) contextLoader;
			smartContextLoader.processContextConfiguration(configAttributes);
			locations.addAll(0, Arrays.asList(configAttributes.getLocations()));
			classes.addAll(0, Arrays.asList(configAttributes.getClasses()));
		}
		else {
			String[] processedLocations = contextLoader.processLocations(
					configAttributes.getDeclaringClass(), configAttributes.getLocations());
			locations.addAll(0, Arrays.asList(processedLocations));
			// Legacy ContextLoaders don't know how to process classes
		}
		initializers.addAll(0, Arrays.asList(configAttributes.getInitializers()));
		if (!configAttributes.isInheritLocations()) {
			break;
		}
	}

	Set<ContextCustomizer> contextCustomizers = getContextCustomizers(testClass,
			Collections.unmodifiableList(configAttributesList));

	Assert.state(!(requireLocationsClassesOrInitializers &&
			areAllEmpty(locations, classes, initializers, contextCustomizers)), () -> String.format(
			"%s was unable to detect defaults, and no ApplicationContextInitializers " +
			"or ContextCustomizers were declared for context configuration attributes %s",
			contextLoader.getClass().getSimpleName(), configAttributesList));

	MergedTestPropertySources mergedTestPropertySources =
			TestPropertySourceUtils.buildMergedTestPropertySources(testClass);
	MergedContextConfiguration mergedConfig = new MergedContextConfiguration(testClass,
			StringUtils.toStringArray(locations), ClassUtils.toClassArray(classes),
			ApplicationContextInitializerUtils.resolveInitializerClasses(configAttributesList),
			ActiveProfilesUtils.resolveActiveProfiles(testClass),
			mergedTestPropertySources.getLocations(),
			mergedTestPropertySources.getProperties(),
			contextCustomizers, contextLoader, cacheAwareContextLoaderDelegate, parentConfig);

	return processMergedContextConfiguration(mergedConfig);
}
 
Example 13
Source Project: spring-analysis-note   Source File: BootstrapWithTestInterface.java    License: MIT License 4 votes vote down vote up
@Override
protected List<ContextCustomizerFactory> getContextCustomizerFactories() {
	return singletonList(
		(ContextCustomizerFactory) (testClass, configAttributes) -> (ContextCustomizer) (context,
				mergedConfig) -> context.getBeanFactory().registerSingleton("foo", "foo"));
}
 
Example 14
/**
 * Build the {@link MergedContextConfiguration merged context configuration}
 * for the supplied {@link Class testClass}, context configuration attributes,
 * and parent context configuration.
 * @param testClass the test class for which the {@code MergedContextConfiguration}
 * should be built (must not be {@code null})
 * @param configAttributesList the list of context configuration attributes for the
 * specified test class, ordered <em>bottom-up</em> (i.e., as if we were
 * traversing up the class hierarchy); never {@code null} or empty
 * @param parentConfig the merged context configuration for the parent application
 * context in a context hierarchy, or {@code null} if there is no parent
 * @param cacheAwareContextLoaderDelegate the cache-aware context loader delegate to
 * be passed to the {@code MergedContextConfiguration} constructor
 * @param requireLocationsClassesOrInitializers whether locations, classes, or
 * initializers are required; typically {@code true} but may be set to {@code false}
 * if the configured loader supports empty configuration
 * @return the merged context configuration
 * @see #resolveContextLoader
 * @see ContextLoaderUtils#resolveContextConfigurationAttributes
 * @see SmartContextLoader#processContextConfiguration
 * @see ContextLoader#processLocations
 * @see ActiveProfilesUtils#resolveActiveProfiles
 * @see ApplicationContextInitializerUtils#resolveInitializerClasses
 * @see MergedContextConfiguration
 */
private MergedContextConfiguration buildMergedContextConfiguration(Class<?> testClass,
		List<ContextConfigurationAttributes> configAttributesList, @Nullable MergedContextConfiguration parentConfig,
		CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate,
		boolean requireLocationsClassesOrInitializers) {

	Assert.notEmpty(configAttributesList, "ContextConfigurationAttributes list must not be null or empty");

	ContextLoader contextLoader = resolveContextLoader(testClass, configAttributesList);
	List<String> locations = new ArrayList<>();
	List<Class<?>> classes = new ArrayList<>();
	List<Class<?>> initializers = new ArrayList<>();

	for (ContextConfigurationAttributes configAttributes : configAttributesList) {
		if (logger.isTraceEnabled()) {
			logger.trace(String.format("Processing locations and classes for context configuration attributes %s",
					configAttributes));
		}
		if (contextLoader instanceof SmartContextLoader) {
			SmartContextLoader smartContextLoader = (SmartContextLoader) contextLoader;
			smartContextLoader.processContextConfiguration(configAttributes);
			locations.addAll(0, Arrays.asList(configAttributes.getLocations()));
			classes.addAll(0, Arrays.asList(configAttributes.getClasses()));
		}
		else {
			String[] processedLocations = contextLoader.processLocations(
					configAttributes.getDeclaringClass(), configAttributes.getLocations());
			locations.addAll(0, Arrays.asList(processedLocations));
			// Legacy ContextLoaders don't know how to process classes
		}
		initializers.addAll(0, Arrays.asList(configAttributes.getInitializers()));
		if (!configAttributes.isInheritLocations()) {
			break;
		}
	}

	Set<ContextCustomizer> contextCustomizers = getContextCustomizers(testClass,
			Collections.unmodifiableList(configAttributesList));

	Assert.state(!(requireLocationsClassesOrInitializers &&
			areAllEmpty(locations, classes, initializers, contextCustomizers)), () -> String.format(
			"%s was unable to detect defaults, and no ApplicationContextInitializers " +
			"or ContextCustomizers were declared for context configuration attributes %s",
			contextLoader.getClass().getSimpleName(), configAttributesList));

	MergedTestPropertySources mergedTestPropertySources =
			TestPropertySourceUtils.buildMergedTestPropertySources(testClass);
	MergedContextConfiguration mergedConfig = new MergedContextConfiguration(testClass,
			StringUtils.toStringArray(locations), ClassUtils.toClassArray(classes),
			ApplicationContextInitializerUtils.resolveInitializerClasses(configAttributesList),
			ActiveProfilesUtils.resolveActiveProfiles(testClass),
			mergedTestPropertySources.getLocations(),
			mergedTestPropertySources.getProperties(),
			contextCustomizers, contextLoader, cacheAwareContextLoaderDelegate, parentConfig);

	return processMergedContextConfiguration(mergedConfig);
}
 
Example 15
Source Project: java-technology-stack   Source File: BootstrapWithTestInterface.java    License: MIT License 4 votes vote down vote up
@Override
protected List<ContextCustomizerFactory> getContextCustomizerFactories() {
	return singletonList(
		(ContextCustomizerFactory) (testClass, configAttributes) -> (ContextCustomizer) (context,
				mergedConfig) -> context.getBeanFactory().registerSingleton("foo", "foo"));
}
 
Example 16
@Test
public void shouldIgnoreNonSpringBootTestClass() {
    ContextCustomizer customizer = factory.createContextCustomizer(NonEmbeddedServerTestClass.class, null);

    assertThat(customizer).isNull();
}
 
Example 17
@Test
public void shouldIgnoreNonEmbeddedServerTestClass() {
    ContextCustomizer customizer = factory.createContextCustomizer(NonTestClass.class, null);

    assertThat(customizer).isNull();
}
 
Example 18
@Nullable
private ContextCustomizer createContextCustomizer(Class<?> testClass) {
	return this.factory.createContextCustomizer(testClass, Collections.emptyList());
}
 
Example 19
/**
 * Create a new {@code WebMergedContextConfiguration} instance for the
 * supplied parameters.
 * <p>If a {@code null} value is supplied for {@code locations},
 * {@code classes}, {@code activeProfiles}, {@code propertySourceLocations},
 * or {@code propertySourceProperties} an empty array will be stored instead.
 * If a {@code null} value is supplied for {@code contextInitializerClasses}
 * or {@code contextCustomizers}, an empty set will be stored instead.
 * If an <em>empty</em> value is supplied for the {@code resourceBasePath}
 * an empty string will be used. Furthermore, active profiles will be sorted,
 * and duplicate profiles will be removed.
 * @param testClass the test class for which the configuration was merged
 * @param locations the merged context resource locations
 * @param classes the merged annotated classes
 * @param contextInitializerClasses the merged context initializer classes
 * @param activeProfiles the merged active bean definition profiles
 * @param propertySourceLocations the merged {@code PropertySource} locations
 * @param propertySourceProperties the merged {@code PropertySource} properties
 * @param contextCustomizers the context customizers
 * @param resourceBasePath the resource path to the root directory of the web application
 * @param contextLoader the resolved {@code ContextLoader}
 * @param cacheAwareContextLoaderDelegate a cache-aware context loader
 * delegate with which to retrieve the parent context
 * @param parent the parent configuration or {@code null} if there is no parent
 * @since 4.3
 */
public WebMergedContextConfiguration(Class<?> testClass, @Nullable String[] locations, @Nullable Class<?>[] classes,
		@Nullable Set<Class<? extends ApplicationContextInitializer<?>>> contextInitializerClasses,
		@Nullable String[] activeProfiles, @Nullable String[] propertySourceLocations, @Nullable String[] propertySourceProperties,
		@Nullable Set<ContextCustomizer> contextCustomizers, String resourceBasePath, ContextLoader contextLoader,
		CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate, @Nullable MergedContextConfiguration parent) {

	super(testClass, locations, classes, contextInitializerClasses, activeProfiles, propertySourceLocations,
		propertySourceProperties, contextCustomizers, contextLoader, cacheAwareContextLoaderDelegate, parent);

	this.resourceBasePath = (StringUtils.hasText(resourceBasePath) ? resourceBasePath : "");
}
 
Example 20
/**
 * Create a new {@code WebMergedContextConfiguration} instance for the
 * supplied parameters.
 * <p>If a {@code null} value is supplied for {@code locations},
 * {@code classes}, {@code activeProfiles}, {@code propertySourceLocations},
 * or {@code propertySourceProperties} an empty array will be stored instead.
 * If a {@code null} value is supplied for {@code contextInitializerClasses}
 * or {@code contextCustomizers}, an empty set will be stored instead.
 * If an <em>empty</em> value is supplied for the {@code resourceBasePath}
 * an empty string will be used. Furthermore, active profiles will be sorted,
 * and duplicate profiles will be removed.
 * @param testClass the test class for which the configuration was merged
 * @param locations the merged context resource locations
 * @param classes the merged annotated classes
 * @param contextInitializerClasses the merged context initializer classes
 * @param activeProfiles the merged active bean definition profiles
 * @param propertySourceLocations the merged {@code PropertySource} locations
 * @param propertySourceProperties the merged {@code PropertySource} properties
 * @param contextCustomizers the context customizers
 * @param resourceBasePath the resource path to the root directory of the web application
 * @param contextLoader the resolved {@code ContextLoader}
 * @param cacheAwareContextLoaderDelegate a cache-aware context loader
 * delegate with which to retrieve the parent context
 * @param parent the parent configuration or {@code null} if there is no parent
 * @since 4.3
 */
public WebMergedContextConfiguration(Class<?> testClass, @Nullable String[] locations, @Nullable Class<?>[] classes,
		@Nullable Set<Class<? extends ApplicationContextInitializer<?>>> contextInitializerClasses,
		@Nullable String[] activeProfiles, @Nullable String[] propertySourceLocations, @Nullable String[] propertySourceProperties,
		@Nullable Set<ContextCustomizer> contextCustomizers, String resourceBasePath, ContextLoader contextLoader,
		CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate, @Nullable MergedContextConfiguration parent) {

	super(testClass, locations, classes, contextInitializerClasses, activeProfiles, propertySourceLocations,
		propertySourceProperties, contextCustomizers, contextLoader, cacheAwareContextLoaderDelegate, parent);

	this.resourceBasePath = (StringUtils.hasText(resourceBasePath) ? resourceBasePath : "");
}
 
Example 21
Source Project: spring-analysis-note   Source File: AbstractContextLoader.java    License: MIT License 2 votes vote down vote up
/**
 * Customize the {@link ConfigurableApplicationContext} created by this
 * {@code ContextLoader} <em>after</em> bean definitions have been loaded
 * into the context but <em>before</em> the context has been refreshed.
 * <p>The default implementation delegates to all
 * {@link MergedContextConfiguration#getContextCustomizers context customizers}
 * that have been registered with the supplied {@code mergedConfig}.
 * @param context the newly created application context
 * @param mergedConfig the merged context configuration
 * @since 4.3
 */
protected void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
	for (ContextCustomizer contextCustomizer : mergedConfig.getContextCustomizers()) {
		contextCustomizer.customizeContext(context, mergedConfig);
	}
}
 
Example 22
Source Project: java-technology-stack   Source File: AbstractContextLoader.java    License: MIT License 2 votes vote down vote up
/**
 * Customize the {@link ConfigurableApplicationContext} created by this
 * {@code ContextLoader} <em>after</em> bean definitions have been loaded
 * into the context but <em>before</em> the context has been refreshed.
 * <p>The default implementation delegates to all
 * {@link MergedContextConfiguration#getContextCustomizers context customizers}
 * that have been registered with the supplied {@code mergedConfig}.
 * @param context the newly created application context
 * @param mergedConfig the merged context configuration
 * @since 4.3
 */
protected void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
	for (ContextCustomizer contextCustomizer : mergedConfig.getContextCustomizers()) {
		contextCustomizer.customizeContext(context, mergedConfig);
	}
}