类org.springframework.test.context.ContextCustomizer源码实例Demo

下面列出了怎么用org.springframework.test.context.ContextCustomizer的API类实例代码及写法,或者点击链接到github查看源代码。

@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;
}
 
@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;
}
 
@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;
}
 
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;
}
 
@Override
protected List<ContextCustomizerFactory> getContextCustomizerFactories() {
	return singletonList(
		(ContextCustomizerFactory) (testClass, configAttributes) ->
			(ContextCustomizer) (context, mergedConfig) -> context.getBeanFactory().registerSingleton("foo", "foo")
	);
}
 
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;
}
 
@Override
protected List<ContextCustomizerFactory> getContextCustomizerFactories() {
	return singletonList(
		(ContextCustomizerFactory) (testClass, configAttributes) ->
			(ContextCustomizer) (context, mergedConfig) -> context.getBeanFactory().registerSingleton("foo", "foo")
	);
}
 
@Override
public ContextCustomizer createContextCustomizer(Class<?> testClass,
    List<ContextConfigurationAttributes> configAttributes) {

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

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

    assertThat(customizer).isNotNull();
    assertThat(customizer).isInstanceOf(VertxWebTestClientContextCustomizer.class);
}
 
@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;
}
 
源代码11 项目: moduliths   文件: ModuleContextCustomizerFactory.java
@Override
public ContextCustomizer createContextCustomizer(Class<?> testClass,
		List<ContextConfigurationAttributes> configAttributes) {

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

	return moduleTest == null ? null : new ModuleContextCustomizer(testClass);
}
 
/**
 * 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);
}
 
@Override
protected List<ContextCustomizerFactory> getContextCustomizerFactories() {
	return singletonList(
		(ContextCustomizerFactory) (testClass, configAttributes) -> (ContextCustomizer) (context,
				mergedConfig) -> context.getBeanFactory().registerSingleton("foo", "foo"));
}
 
/**
 * 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);
}
 
@Override
protected List<ContextCustomizerFactory> getContextCustomizerFactories() {
	return singletonList(
		(ContextCustomizerFactory) (testClass, configAttributes) -> (ContextCustomizer) (context,
				mergedConfig) -> context.getBeanFactory().registerSingleton("foo", "foo"));
}
 
@Test
public void shouldIgnoreNonSpringBootTestClass() {
    ContextCustomizer customizer = factory.createContextCustomizer(NonEmbeddedServerTestClass.class, null);

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

    assertThat(customizer).isNull();
}
 
@Nullable
private ContextCustomizer createContextCustomizer(Class<?> testClass) {
	return this.factory.createContextCustomizer(testClass, Collections.emptyList());
}
 
/**
 * 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 : "");
}
 
/**
 * 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 : "");
}
 
/**
 * 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);
	}
}
 
/**
 * 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);
	}
}
 
 同包方法