org.springframework.boot.test.context.assertj.AssertableApplicationContext Java Examples

The following examples show how to use org.springframework.boot.test.context.assertj.AssertableApplicationContext. 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: AppBrokerAutoConfigurationTest.java    From spring-cloud-app-broker with Apache License 2.0 6 votes vote down vote up
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");
}
 
Example #2
Source File: ProjectAssetTester.java    From initializr with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
	});
}
 
Example #3
Source File: CloudFoundryClientAutoConfigurationTest.java    From spring-cloud-cloudfoundry with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #4
Source File: TaskJobLauncherAutoConfigurationTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #5
Source File: FeignClientFactoryTests.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #6
Source File: JmsTracingConfigurationTest.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
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();
	}
}
 
Example #7
Source File: CredHubAutoConfigurationTests.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example #8
Source File: IapAuthenticationAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #9
Source File: JmsTracingConfigurationTest.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
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();
	}
}
 
Example #10
Source File: JmsTracingConfigurationTest.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
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();
	}
}
 
Example #11
Source File: TraceHttpAutoConfigurationTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
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);
	};
}
 
Example #12
Source File: TraceBaggageConfigurationTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example #13
Source File: EventFlowsAutoConfigurationTest.java    From spring-cloud-open-service-broker with Apache License 2.0 4 votes vote down vote up
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));
}
 
Example #14
Source File: RefreshScopedAutoConfigurationTest.java    From resilience4j with Apache License 2.0 4 votes vote down vote up
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()));
}
 
Example #15
Source File: TraceAutoConfigurationCustomizersTests.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
private void shouldNotOverrideTheDefaults(AssertableApplicationContext context) {
	then(context.getBean(Sampler.class)).isSameAs(Sampler.ALWAYS_SAMPLE);
}
 
Example #16
Source File: TraceBaggageConfigurationTests.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example #17
Source File: HazelcastJetAutoConfigurationClientTests.java    From hazelcast-jet-contrib with Apache License 2.0 4 votes vote down vote up
private static ContextConsumer<AssertableApplicationContext> assertSpecificHazelcastJetClient(String label) {
    return (context) -> assertThat(context).getBean(JetInstance.class).isInstanceOf(JetInstance.class)
                                           .has(labelEqualTo(label));
}
 
Example #18
Source File: DmnEngineAutoConfigurationTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
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");
}
 
Example #19
Source File: GcpContextAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
private ContextConsumer<AssertableApplicationContext> checkNumberOfBeansOfTypeGcpProjectIdProvider(int count) {
	return context -> assertThat(context
			.getBeansOfType(GcpProjectIdProvider.class).size())
					.isEqualTo(count);
}
 
Example #20
Source File: AppBrokerAutoConfigurationTest.java    From spring-cloud-app-broker with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example #21
Source File: InfluxDB2AutoConfigurationTest.java    From influxdb-client-java with MIT License 4 votes vote down vote up
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();
}
 
Example #22
Source File: HazelcastJetAutoConfigurationServerTests.java    From hazelcast-jet-contrib with Apache License 2.0 4 votes vote down vote up
private static ContextConsumer<AssertableApplicationContext> assertSpecificJetImdgServer(String clusterName) {
    return context -> {
        JetConfig jetConfig = context.getBean(JetInstance.class).getConfig();
        assertThat(jetConfig.getHazelcastConfig().getClusterName()).isEqualTo(clusterName);
    };
}
 
Example #23
Source File: HazelcastJetAutoConfigurationServerTests.java    From hazelcast-jet-contrib with Apache License 2.0 4 votes vote down vote up
private static ContextConsumer<AssertableApplicationContext> assertSpecificJetServer(String suffix) {
    return context -> {
        JetConfig jetConfig = context.getBean(JetInstance.class).getConfig();
        assertThat(jetConfig.getProperties().getProperty("foo")).isEqualTo("bar-" + suffix);
    };
}
 
Example #24
Source File: TestUtils.java    From moduliths with Apache License 2.0 3 votes vote down vote up
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);
			});
		});
	}