类org.springframework.boot.test.context.assertj.AssertableApplicationContext源码实例Demo

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

private void assertPropertiesLoaded(AssertableApplicationContext context) {
	BrokeredServices brokeredServices = context.getBean(BrokeredServices.class);
	assertThat(brokeredServices).hasSize(2);

	assertThat(brokeredServices.get(0).getServiceName()).isEqualTo("service1");
	assertThat(brokeredServices.get(0).getPlanName()).isEqualTo("service1-plan1");

	assertThat(brokeredServices.get(0).getApps().get(0).getName()).isEqualTo("app1");
	assertThat(brokeredServices.get(0).getApps().get(0).getPath()).isEqualTo("classpath:app1.jar");
	assertThat(brokeredServices.get(0).getApps().get(0).getProperties().get("memory")).isEqualTo("1G");
	assertThat(brokeredServices.get(0).getApps().get(0).getProperties().get("instances")).isNull();

	assertThat(brokeredServices.get(0).getApps().get(1).getName()).isEqualTo("app2");
	assertThat(brokeredServices.get(0).getApps().get(1).getPath()).isEqualTo("classpath:app2.jar");
	assertThat(brokeredServices.get(0).getApps().get(1).getProperties().get("memory")).isEqualTo("2G");
	assertThat(brokeredServices.get(0).getApps().get(1).getProperties().get("instances")).isEqualTo("2");

	assertThat(brokeredServices.get(1).getServiceName()).isEqualTo("service2");
	assertThat(brokeredServices.get(1).getPlanName()).isEqualTo("service2-plan1");

	assertThat(brokeredServices.get(1).getApps().get(0).getName()).isEqualTo("app3");
	assertThat(brokeredServices.get(1).getApps().get(0).getPath()).isEqualTo("classpath:app3.jar");
}
 
@SuppressWarnings({ "unchecked", "ConstantConditions" })
private void defaultClientUsed(AssertableApplicationContext context) {
	Proxy target = context.getBean(FeignClientFactoryBean.class).getTarget();
	Object invocationHandler = ReflectionTestUtils.getField(target, "h");
	Map<Method, InvocationHandlerFactory.MethodHandler> dispatch = (Map<Method, InvocationHandlerFactory.MethodHandler>) ReflectionTestUtils
			.getField(invocationHandler, "dispatch");
	Method key = new ArrayList<>(dispatch.keySet()).get(0);
	Object client = ReflectionTestUtils.getField(dispatch.get(key), "client");
	assertThat(client).isInstanceOf(Client.Default.class);
}
 
private void assertPropertiesConfigured(AssertableApplicationContext context) {
	assertThat(context).hasSingleBean(CredHubProperties.class);
	CredHubProperties properties = context.getBean(CredHubProperties.class);
	assertThat(properties.getUrl()).isEqualTo("https://localhost");
	assertThat(properties.getOauth2().getRegistrationId()).isEqualTo("test-client");

	assertThat(context).hasSingleBean(ClientOptions.class);
	ClientOptions options = context.getBean(ClientOptions.class);
	assertThat(options.getConnectionTimeout()).isEqualTo(Duration.ofMillis(30));
	assertThat(options.getReadTimeout()).isEqualTo(Duration.ofMillis(60));
}
 
private void verifyJwtBeans(AssertableApplicationContext context) {
	JwtDecoder jwtDecoder =  context.getBean(JwtDecoder.class);
	assertThat(jwtDecoder).isNotNull();
	assertThat(jwtDecoder).isInstanceOf(NimbusJwtDecoderJwkSupport.class);

	BearerTokenResolver resolver = context.getBean(BearerTokenResolver.class);
	assertThat(resolver).isNotNull();
	assertThat(resolver.resolve(this.mockIapRequest)).isEqualTo("very fake jwt");

	assertThat(resolver.resolve(this.mockNonIapRequest)).isNull();
}
 
private ContextConsumer<AssertableApplicationContext> thenCompositeHttpServerSamplerOf(
		SamplerFunction<HttpRequest> instance) {
	return (context) -> {

		SamplerFunction<HttpRequest> serverSampler = context
				.getBean(HttpTracing.class).serverRequestSampler();

		then(serverSampler).isInstanceOf(CompositeHttpSampler.class);

		then(((CompositeHttpSampler) serverSampler).left)
				.isInstanceOf(SkipPatternHttpServerSampler.class);
		then(((CompositeHttpSampler) serverSampler).right).isSameAs(instance);
	};
}
 
static ListAssert<Tuple> assertThatBaggageFieldNameToKeyNames(
		AssertableApplicationContext context) {
	return assertThat(context.getBean(Propagation.Factory.class))
			.extracting("configs").asInstanceOf(InstanceOfAssertFactories.ARRAY)
			.extracting("field.name", "keyNames.toArray")
			.asInstanceOf(InstanceOfAssertFactories.list(Tuple.class));
}
 
static void checkConnection(AssertableApplicationContext ctx) throws JMSException {
	// Not using try-with-resources as that doesn't exist in JMS 1.1
	Connection con = ctx.getBean(ConnectionFactory.class).createConnection();
	try {
		con.setExceptionListener(exception -> {
		});
		assertThat(con.getExceptionListener().getClass().getName())
				.startsWith("brave.jms.TracingExceptionListener");
	}
	finally {
		con.close();
	}
}
 
static void checkXAConnection(AssertableApplicationContext ctx) throws JMSException {
	// Not using try-with-resources as that doesn't exist in JMS 1.1
	XAConnection con = ctx.getBean(XAConnectionFactory.class).createXAConnection();
	try {
		con.setExceptionListener(exception -> {
		});
		assertThat(con.getExceptionListener().getClass().getName())
				.startsWith("brave.jms.TracingExceptionListener");
	}
	finally {
		con.close();
	}
}
 
static void checkTopicConnection(AssertableApplicationContext ctx)
		throws JMSException {
	// Not using try-with-resources as that doesn't exist in JMS 1.1
	TopicConnection con = ctx.getBean(TopicConnectionFactory.class)
			.createTopicConnection();
	try {
		con.setExceptionListener(exception -> {
		});
		assertThat(con.getExceptionListener().getClass().getName())
				.startsWith("brave.jms.TracingExceptionListener");
	}
	finally {
		con.close();
	}
}
 
private void validateJobNames(AssertableApplicationContext context, String jobNames)
		throws Exception {
	JobLauncherCommandLineRunner jobLauncherCommandLineRunner = context
			.getBean(JobLauncherCommandLineRunner.class);

	Object names = ReflectionTestUtils.getField(jobLauncherCommandLineRunner,
			"jobNames");
	assertThat(names).isEqualTo(jobNames);
}
 
private void assertCloudFoundryClientBeansPresent(
		AssertableApplicationContext context) {
	assertThat(context).hasSingleBean(ReactorCloudFoundryClient.class);
	assertThat(context).hasSingleBean(DefaultCloudFoundryOperations.class);
	assertThat(context).hasSingleBean(DefaultConnectionContext.class);
	assertThat(context).hasSingleBean(DopplerClient.class);
	assertThat(context).hasSingleBean(RoutingClient.class);
	assertThat(context).hasSingleBean(PasswordGrantTokenProvider.class);
	assertThat(context).hasSingleBean(ReactorUaaClient.class);
}
 
源代码12 项目: initializr   文件: ProjectAssetTester.java
/**
 * Configure a {@link ProjectGenerationContext} using the specified
 * {@code description} and use the {@link ContextConsumer} to assert the context.
 * @param description the description of the project to configure
 * @param consumer the consumer of the created {@link ProjectGenerationContext}
 * @see ApplicationContextRunner#run(ContextConsumer)
 */
public void configure(MutableProjectDescription description,
		ContextConsumer<AssertableApplicationContext> consumer) {
	invokeProjectGeneration(description, (contextInitializer) -> {
		new ApplicationContextRunner(ProjectGenerationContext::new).withInitializer((ctx) -> {
			ProjectGenerationContext projectGenerationContext = (ProjectGenerationContext) ctx;
			projectGenerationContext.registerBean(ProjectDescription.class, () -> description);
			contextInitializer.accept(projectGenerationContext);
		}).run(consumer);
		return null;
	});
}
 
private static ContextConsumer<AssertableApplicationContext> assertSpecificHazelcastJetClient(String label) {
    return (context) -> assertThat(context).getBean(JetInstance.class).isInstanceOf(JetInstance.class)
                                           .has(labelEqualTo(label));
}
 
private static ContextConsumer<AssertableApplicationContext> assertSpecificJetServer(String suffix) {
    return context -> {
        JetConfig jetConfig = context.getBean(JetInstance.class).getConfig();
        assertThat(jetConfig.getProperties().getProperty("foo")).isEqualTo("bar-" + suffix);
    };
}
 
private static ContextConsumer<AssertableApplicationContext> assertSpecificJetImdgServer(String clusterName) {
    return context -> {
        JetConfig jetConfig = context.getBean(JetInstance.class).getConfig();
        assertThat(jetConfig.getHazelcastConfig().getClusterName()).isEqualTo(clusterName);
    };
}
 
private int getReadTimeoutProperty(AssertableApplicationContext context) {
    InfluxDBClient influxDB = context.getBean(InfluxDBClient.class);
    Retrofit retrofit = (Retrofit) ReflectionTestUtils.getField(influxDB, "retrofit");
    OkHttpClient callFactory = (OkHttpClient) retrofit.callFactory();
    return callFactory.readTimeoutMillis();
}
 
private void assertBeansCreated(AssertableApplicationContext context) {
	assertThat(context).hasSingleBean(DeployerClient.class);
	assertThat(context).hasSingleBean(ManagementClient.class);
	assertThat(context).hasSingleBean(BrokeredServices.class);

	assertThat(context).hasSingleBean(ServiceInstanceStateRepository.class);
	assertThat(context).hasSingleBean(ServiceInstanceBindingStateRepository.class);

	assertThat(context).hasSingleBean(BackingAppDeploymentService.class);
	assertThat(context).hasSingleBean(BackingAppManagementService.class);
	assertThat(context).hasSingleBean(BackingServicesProvisionService.class);

	assertThat(context).hasSingleBean(BackingApplicationsParametersTransformationService.class);
	assertThat(context).hasSingleBean(EnvironmentMappingParametersTransformerFactory.class);
	assertThat(context).hasSingleBean(PropertyMappingParametersTransformerFactory.class);

	assertThat(context).hasSingleBean(BackingServicesParametersTransformationService.class);
	assertThat(context).hasSingleBean(ParameterMappingParametersTransformerFactory.class);

	assertThat(context).hasSingleBean(CredentialProviderService.class);
	assertThat(context).hasSingleBean(SpringSecurityBasicAuthCredentialProviderFactory.class);
	assertThat(context).hasSingleBean(SpringSecurityOAuth2CredentialProviderFactory.class);

	assertThat(context).hasSingleBean(TargetService.class);

	assertThat(context).hasSingleBean(SpacePerServiceInstance.class);
	assertThat(context).hasSingleBean(ServiceInstanceGuidSuffix.class);

	assertThat(context).hasSingleBean(AppDeploymentCreateServiceInstanceWorkflow.class);
	assertThat(context).hasSingleBean(AppDeploymentDeleteServiceInstanceWorkflow.class);
	assertThat(context).hasSingleBean(AppDeploymentUpdateServiceInstanceWorkflow.class);

	assertThat(context).doesNotHaveBean(CreateServiceInstanceAppBindingWorkflow.class);
	assertThat(context).doesNotHaveBean(CreateServiceInstanceRouteBindingWorkflow.class);
	assertThat(context).doesNotHaveBean(DeleteServiceInstanceBindingWorkflow.class);

	assertThat(context)
		.hasSingleBean(CredentialGenerator.class)
		.getBean(CredentialGenerator.class)
		.isExactlyInstanceOf(SimpleCredentialGenerator.class);
}
 
private ContextConsumer<AssertableApplicationContext> checkNumberOfBeansOfTypeGcpProjectIdProvider(int count) {
	return context -> assertThat(context
			.getBeansOfType(GcpProjectIdProvider.class).size())
					.isEqualTo(count);
}
 
protected void assertAutoDeploymentWithAppEngine(AssertableApplicationContext context) {
    DmnRepositoryService repositoryService = context.getBean(DmnRepositoryService.class);
    List<DmnDecision> definitions = repositoryService.createDecisionQuery().list();
    assertThat(definitions)
        .extracting(DmnDecision::getKey, DmnDecision::getName)
        .containsExactlyInAnyOrder(
            tuple("RiskRating", "Risk Rating Decision Table"),
            tuple("simple", "Full Decision"),
            tuple("strings1", "Simple decision"),
            tuple("strings2", "Simple decision"),
            tuple("managerApprovalNeeded", "Manager approval needed2")
        );
    
    DmnDecision definition = repositoryService.createDecisionQuery().latestVersion().decisionKey("strings1").singleResult();
    assertThat(definition.getVersion()).isOne();
    
    definition = repositoryService.createDecisionQuery().latestVersion().decisionKey("managerApprovalNeeded").singleResult();
    assertThat(definition.getVersion()).isOne();
    
    List<DmnDeployment> deployments = repositoryService.createDeploymentQuery().list();

    assertThat(deployments).hasSize(2)
        .extracting(DmnDeployment::getName)
        .containsExactlyInAnyOrder("SpringBootAutoDeployment", "vacationRequest.zip");
    
    AppRepositoryService appRepositoryService = context.getBean(AppRepositoryService.class);
    List<AppDefinition> appDefinitions = appRepositoryService.createAppDefinitionQuery().list();
    
    assertThat(appDefinitions)
        .extracting(AppDefinition::getKey)
        .contains("simpleApp", "vacationRequestApp");
    
    AppDefinition appDefinition = appRepositoryService.createAppDefinitionQuery().latestVersion().appDefinitionKey("simpleApp").singleResult();
    assertThat(appDefinition.getVersion()).isOne();
    
    appDefinition = appRepositoryService.createAppDefinitionQuery().latestVersion().appDefinitionKey("vacationRequestApp").singleResult();
    assertThat(appDefinition.getVersion()).isOne();
    
    List<AppDeployment> appDeployments = appRepositoryService.createDeploymentQuery().list();
    assertThat(appDeployments).hasSize(3)
        .extracting(AppDeployment::getName)
        .containsExactlyInAnyOrder("simple.bar", "vacationRequest.zip", "processTask.bar");
}
 
private void assertBeans(AssertableApplicationContext context) {
	assertThat(context)
			.getBean(CreateServiceInstanceEventFlowRegistry.class)
			.isNotNull();

	assertThat(context)
			.getBean(UpdateServiceInstanceEventFlowRegistry.class)
			.isNotNull();

	assertThat(context)
			.getBean(DeleteServiceInstanceEventFlowRegistry.class)
			.isNotNull();

	assertThat(context)
			.getBean(AsyncOperationServiceInstanceEventFlowRegistry.class)
			.isNotNull();

	assertThat(context)
			.getBean(CreateServiceInstanceBindingEventFlowRegistry.class)
			.isNotNull();

	assertThat(context)
			.getBean(DeleteServiceInstanceBindingEventFlowRegistry.class)
			.isNotNull();

	assertThat(context)
			.getBean(AsyncOperationServiceInstanceBindingEventFlowRegistry.class)
			.isNotNull();

	assertThat(context)
			.getBean(EventFlowRegistries.class)
			.isNotNull();

	EventFlowRegistries eventFlowRegistries = context.getBean(EventFlowRegistries.class);
	assertThat(eventFlowRegistries.getCreateInstanceRegistry())
			.isEqualTo(context.getBean(CreateServiceInstanceEventFlowRegistry.class));

	assertThat(eventFlowRegistries.getUpdateInstanceRegistry())
			.isEqualTo(context.getBean(UpdateServiceInstanceEventFlowRegistry.class));

	assertThat(eventFlowRegistries.getDeleteInstanceRegistry())
			.isEqualTo(context.getBean(DeleteServiceInstanceEventFlowRegistry.class));

	assertThat(eventFlowRegistries.getAsyncOperationRegistry())
			.isEqualTo(context.getBean(AsyncOperationServiceInstanceEventFlowRegistry.class));

	assertThat(eventFlowRegistries.getCreateInstanceBindingRegistry())
			.isEqualTo(context.getBean(CreateServiceInstanceBindingEventFlowRegistry.class));

	assertThat(eventFlowRegistries.getDeleteInstanceBindingRegistry())
			.isEqualTo(context.getBean(DeleteServiceInstanceBindingEventFlowRegistry.class));

	assertThat(eventFlowRegistries.getAsyncOperationBindingRegistry())
			.isEqualTo(context.getBean(AsyncOperationServiceInstanceBindingEventFlowRegistry.class));
}
 
static AbstractListAssert<?, List<? extends String>, String, ObjectAssert<String>> assertThatFieldNamesToTag(
		AssertableApplicationContext context) {
	return assertThat(context.getBean(SpanHandler.class))
			.isInstanceOf(BaggageTagSpanHandler.class).extracting("fieldsToTag")
			.asInstanceOf(array(BaggageField[].class)).extracting(BaggageField::name);
}
 
private void shouldNotOverrideTheDefaults(AssertableApplicationContext context) {
	then(context.getBean(Sampler.class)).isSameAs(Sampler.ALWAYS_SAMPLE);
}
 
private static void testRefreshScoped(AssertableApplicationContext context, String beanName) {
    BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition(beanName);
    MethodMetadata beanMethod = (MethodMetadata) beanDefinition.getSource();

    assertTrue(beanMethod.isAnnotated(RefreshScope.class.getName()));
}
 
源代码24 项目: moduliths   文件: TestUtils.java
public static void assertDependencyMissing(Class<?> testClass, Class<?> expectedMissingDependency) {

		CacheAwareContextLoaderDelegate delegate = new DefaultCacheAwareContextLoaderDelegate();
		BootstrapContext bootstrapContext = new DefaultBootstrapContext(testClass, delegate);

		SpringBootTestContextBootstrapper bootstrapper = new SpringBootTestContextBootstrapper();
		bootstrapper.setBootstrapContext(bootstrapContext);

		MergedContextConfiguration configuration = bootstrapper.buildMergedContextConfiguration();

		AssertableApplicationContext context = AssertableApplicationContext.get(() -> {

			SpringBootContextLoader loader = new SpringBootContextLoader();

			try {

				return (ConfigurableApplicationContext) loader.loadContext(configuration);

			} catch (Exception e) {

				if (e instanceof RuntimeException) {
					throw (RuntimeException) e;
				}

				throw new RuntimeException(e);
			}
		});

		assertThat(context).hasFailed();

		assertThat(context).getFailure().isInstanceOfSatisfying(UnsatisfiedDependencyException.class, it -> {
			assertThat(it.getMostSpecificCause()).isInstanceOfSatisfying(NoSuchBeanDefinitionException.class, ex -> {
				assertThat(ex.getBeanType()).isEqualTo(expectedMissingDependency);
			});
		});
	}
 
 类所在包
 类方法
 同包方法