Search in sources :

Example 1 with ConfigurableBeanFactory

use of cn.taketoday.beans.factory.config.ConfigurableBeanFactory in project today-infrastructure by TAKETODAY.

the class ApplicationTests method runnersAreCalledAfterStartedIsLoggedAndBeforeApplicationReadyEventIsPublished.

@Test
@SuppressWarnings("unchecked")
void runnersAreCalledAfterStartedIsLoggedAndBeforeApplicationReadyEventIsPublished(CapturedOutput output) throws Exception {
    Application application = new Application(ExampleConfig.class);
    ApplicationRunner applicationRunner = mock(ApplicationRunner.class);
    CommandLineRunner commandLineRunner = mock(CommandLineRunner.class);
    application.addInitializers((context) -> {
        ConfigurableBeanFactory beanFactory = context.getBeanFactory();
        beanFactory.registerSingleton("commandLineRunner", (CommandLineRunner) (args) -> {
            assertThat(output).contains("Started");
            commandLineRunner.run(args);
        });
        beanFactory.registerSingleton("applicationRunner", (ApplicationRunner) (args) -> {
            assertThat(output).contains("Started");
            applicationRunner.run(args);
        });
    });
    application.setApplicationType(ApplicationType.NONE_WEB);
    ApplicationListener<ApplicationReadyEvent> eventListener = mock(ApplicationListener.class);
    application.addListeners(eventListener);
    this.context = application.run();
    InOrder applicationRunnerOrder = Mockito.inOrder(eventListener, applicationRunner);
    applicationRunnerOrder.verify(applicationRunner).run(any(ApplicationArguments.class));
    applicationRunnerOrder.verify(eventListener).onApplicationEvent(any(ApplicationReadyEvent.class));
    InOrder commandLineRunnerOrder = Mockito.inOrder(eventListener, commandLineRunner);
    commandLineRunnerOrder.verify(commandLineRunner).run();
    commandLineRunnerOrder.verify(eventListener).onApplicationEvent(any(ApplicationReadyEvent.class));
}
Also used : ConfigurableBeanFactory(cn.taketoday.beans.factory.config.ConfigurableBeanFactory) BeforeEach(org.junit.jupiter.api.BeforeEach) LinkedMultiValueMap(cn.taketoday.core.LinkedMultiValueMap) Resource(cn.taketoday.core.io.Resource) ApplicationEvent(cn.taketoday.context.ApplicationEvent) PostConstruct(jakarta.annotation.PostConstruct) Ordered(cn.taketoday.core.Ordered) PropertySource(cn.taketoday.core.env.PropertySource) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Assertions.assertThatNoException(org.assertj.core.api.Assertions.assertThatNoException) ApplicationContextInitializedEvent(cn.taketoday.framework.context.event.ApplicationContextInitializedEvent) ConfigurableWebEnvironment(cn.taketoday.web.context.ConfigurableWebEnvironment) StandardServletEnvironment(cn.taketoday.web.context.support.StandardServletEnvironment) Map(java.util.Map) ApplicationBuilder(cn.taketoday.framework.builder.ApplicationBuilder) BeanDefinitionRegistry(cn.taketoday.beans.factory.support.BeanDefinitionRegistry) BeanDefinitionOverrideException(cn.taketoday.beans.factory.support.BeanDefinitionOverrideException) ApplicationEnvironmentPreparedEvent(cn.taketoday.framework.context.event.ApplicationEnvironmentPreparedEvent) AbstractApplicationContext(cn.taketoday.context.support.AbstractApplicationContext) BeanNameGenerator(cn.taketoday.beans.factory.support.BeanNameGenerator) Profiles(cn.taketoday.core.env.Profiles) BeanCurrentlyInCreationException(cn.taketoday.beans.factory.BeanCurrentlyInCreationException) ObjectProvider(cn.taketoday.beans.factory.ObjectProvider) Bean(cn.taketoday.context.annotation.Bean) MockEnvironment(cn.taketoday.mock.env.MockEnvironment) Environment(cn.taketoday.core.env.Environment) Mockito.atLeastOnce(org.mockito.Mockito.atLeastOnce) Set(java.util.Set) ContextRefreshedEvent(cn.taketoday.context.event.ContextRefreshedEvent) ConfigurableApplicationContext(cn.taketoday.context.ConfigurableApplicationContext) ApplicationFailedEvent(cn.taketoday.framework.context.event.ApplicationFailedEvent) ApplicationContextException(cn.taketoday.context.ApplicationContextException) CapturedOutput(cn.taketoday.framework.test.system.CapturedOutput) CachedIntrospectionResults(cn.taketoday.beans.CachedIntrospectionResults) TestPropertySourceUtils(cn.taketoday.test.context.support.TestPropertySourceUtils) DefaultBeanNameGenerator(cn.taketoday.beans.factory.support.DefaultBeanNameGenerator) CommandLinePropertySource(cn.taketoday.core.env.CommandLinePropertySource) Mockito.mock(org.mockito.Mockito.mock) AvailabilityChangeEvent(cn.taketoday.framework.availability.AvailabilityChangeEvent) HttpHandler(cn.taketoday.http.server.reactive.HttpHandler) StringUtils(cn.taketoday.util.StringUtils) ConfigurableBeanFactory(cn.taketoday.beans.factory.config.ConfigurableBeanFactory) InstanceSupplier(cn.taketoday.framework.BootstrapRegistry.InstanceSupplier) DefaultResourceLoader(cn.taketoday.core.io.DefaultResourceLoader) Mockito.spy(org.mockito.Mockito.spy) ApplicationReadyEvent(cn.taketoday.framework.context.event.ApplicationReadyEvent) ArrayList(java.util.ArrayList) WebApplicationContext(cn.taketoday.web.WebApplicationContext) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) MultiValueMap(cn.taketoday.core.MultiValueMap) LinkedHashSet(java.util.LinkedHashSet) ArgumentMatchers.isA(org.mockito.ArgumentMatchers.isA) ApplicationPreparedEvent(cn.taketoday.framework.context.event.ApplicationPreparedEvent) Mono(reactor.core.publisher.Mono) AnnotationConfigReactiveWebServerApplicationContext(cn.taketoday.framework.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext) AfterEach(org.junit.jupiter.api.AfterEach) Mockito.never(org.mockito.Mockito.never) Condition(org.assertj.core.api.Condition) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) AnnotationConfigServletWebServerApplicationContext(cn.taketoday.framework.web.servlet.context.AnnotationConfigServletWebServerApplicationContext) MapPropertySource(cn.taketoday.core.env.MapPropertySource) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) Configuration(cn.taketoday.context.annotation.Configuration) NettyReactiveWebServerFactory(cn.taketoday.framework.web.embedded.netty.NettyReactiveWebServerFactory) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ReadinessState(cn.taketoday.framework.availability.ReadinessState) ApplicationStartingEvent(cn.taketoday.framework.context.event.ApplicationStartingEvent) SimpleApplicationEventMulticaster(cn.taketoday.context.event.SimpleApplicationEventMulticaster) ArgumentMatcher(org.mockito.ArgumentMatcher) ApplicationEventMulticaster(cn.taketoday.context.event.ApplicationEventMulticaster) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ClassPathResource(cn.taketoday.core.io.ClassPathResource) AnnotationConfigApplicationContext(cn.taketoday.context.annotation.AnnotationConfigApplicationContext) StandardEnvironment(cn.taketoday.core.env.StandardEnvironment) BeanCreationException(cn.taketoday.beans.factory.BeanCreationException) Lazy(cn.taketoday.context.annotation.Lazy) ApplicationContextInitializer(cn.taketoday.context.ApplicationContextInitializer) ApplicationContext(cn.taketoday.context.ApplicationContext) CompositePropertySource(cn.taketoday.core.env.CompositePropertySource) BDDMockito.willThrow(org.mockito.BDDMockito.willThrow) ConfigurableEnvironment(cn.taketoday.core.env.ConfigurableEnvironment) ApplicationConversionService(cn.taketoday.format.support.ApplicationConversionService) Autowired(cn.taketoday.beans.factory.annotation.Autowired) AnnotationConfigUtils(cn.taketoday.context.annotation.AnnotationConfigUtils) ResourceLoader(cn.taketoday.core.io.ResourceLoader) SmartApplicationListener(cn.taketoday.context.event.SmartApplicationListener) Test(org.junit.jupiter.api.Test) List(java.util.List) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) StaticApplicationContext(cn.taketoday.context.support.StaticApplicationContext) HashMap(java.util.HashMap) ReactiveWebApplicationContext(cn.taketoday.framework.web.reactive.context.ReactiveWebApplicationContext) AtomicReference(java.util.concurrent.atomic.AtomicReference) ApplicationContextAware(cn.taketoday.context.aware.ApplicationContextAware) OutputCaptureExtension(cn.taketoday.framework.test.system.OutputCaptureExtension) ArgumentCaptor(org.mockito.ArgumentCaptor) ApplicationListener(cn.taketoday.context.ApplicationListener) Assertions.assertThatIllegalStateException(org.assertj.core.api.Assertions.assertThatIllegalStateException) InOrder(org.mockito.InOrder) Iterator(java.util.Iterator) UnsatisfiedDependencyException(cn.taketoday.beans.factory.UnsatisfiedDependencyException) BDDMockito.then(org.mockito.BDDMockito.then) TomcatServletWebServerFactory(cn.taketoday.framework.web.embedded.tomcat.TomcatServletWebServerFactory) Mockito(org.mockito.Mockito) AvailabilityState(cn.taketoday.framework.availability.AvailabilityState) LivenessState(cn.taketoday.framework.availability.LivenessState) Collections(java.util.Collections) ApplicationStartedEvent(cn.taketoday.framework.context.event.ApplicationStartedEvent) InOrder(org.mockito.InOrder) ApplicationReadyEvent(cn.taketoday.framework.context.event.ApplicationReadyEvent) Test(org.junit.jupiter.api.Test)

Example 2 with ConfigurableBeanFactory

use of cn.taketoday.beans.factory.config.ConfigurableBeanFactory in project today-infrastructure by TAKETODAY.

the class OnExpressionCondition method getMatchOutcome.

@Override
public ConditionOutcome getMatchOutcome(ConditionEvaluationContext context, AnnotatedTypeMetadata metadata) {
    String expression = metadata.getAnnotation(ConditionalOnExpression.class).getStringValue();
    expression = wrapIfNecessary(expression);
    ConditionMessage.Builder messageBuilder = ConditionMessage.forCondition(ConditionalOnExpression.class, "(" + expression + ")");
    expression = context.getEnvironment().resolvePlaceholders(expression);
    ConfigurableBeanFactory beanFactory = context.getBeanFactory();
    if (beanFactory != null) {
        boolean result = evaluateExpression(beanFactory, expression);
        return new ConditionOutcome(result, messageBuilder.resultedIn(result));
    }
    return ConditionOutcome.noMatch(messageBuilder.because("no BeanFactory available."));
}
Also used : ConfigurableBeanFactory(cn.taketoday.beans.factory.config.ConfigurableBeanFactory)

Example 3 with ConfigurableBeanFactory

use of cn.taketoday.beans.factory.config.ConfigurableBeanFactory in project today-infrastructure by TAKETODAY.

the class ApplicationEventsTestExecutionListener method registerListenerAndResolvableDependencyIfNecessary.

private void registerListenerAndResolvableDependencyIfNecessary(ApplicationContext applicationContext) {
    Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext, "The ApplicationContext for the test must be an AbstractApplicationContext");
    AbstractApplicationContext aac = (AbstractApplicationContext) applicationContext;
    // Synchronize to avoid race condition in parallel test execution
    synchronized (applicationEventsMonitor) {
        boolean notAlreadyRegistered = aac.getApplicationListeners().stream().map(Object::getClass).noneMatch(ApplicationEventsApplicationListener.class::equals);
        if (notAlreadyRegistered) {
            // Register a new ApplicationEventsApplicationListener.
            aac.addApplicationListener(new ApplicationEventsApplicationListener());
            // Register ApplicationEvents as a resolvable dependency for @Autowired support in test classes.
            ConfigurableBeanFactory beanFactory = aac.getBeanFactory();
            beanFactory.registerDependency(ApplicationEvents.class, new ApplicationEventsObjectFactory());
        }
    }
}
Also used : ConfigurableBeanFactory(cn.taketoday.beans.factory.config.ConfigurableBeanFactory) AbstractApplicationContext(cn.taketoday.context.support.AbstractApplicationContext)

Example 4 with ConfigurableBeanFactory

use of cn.taketoday.beans.factory.config.ConfigurableBeanFactory in project today-infrastructure by TAKETODAY.

the class ResetMocksTestExecutionListener method resetMocks.

private void resetMocks(ConfigurableApplicationContext applicationContext, MockReset reset) {
    ConfigurableBeanFactory beanFactory = applicationContext.getBeanFactory();
    String[] names = beanFactory.getBeanDefinitionNames();
    Set<String> instantiatedSingletons = new HashSet<>(Arrays.asList(beanFactory.getSingletonNames()));
    for (String name : names) {
        BeanDefinition definition = beanFactory.getBeanDefinition(name);
        if (definition.isSingleton() && instantiatedSingletons.contains(name)) {
            Object bean = beanFactory.getSingleton(name);
            if (reset.equals(MockReset.get(bean))) {
                Mockito.reset(bean);
            }
        }
    }
    try {
        MockitoBeans mockedBeans = beanFactory.getBean(MockitoBeans.class);
        for (Object mockedBean : mockedBeans) {
            if (reset.equals(MockReset.get(mockedBean))) {
                Mockito.reset(mockedBean);
            }
        }
    } catch (NoSuchBeanDefinitionException ex) {
    // Continue
    }
    if (applicationContext.getParent() != null) {
        resetMocks(applicationContext.getParent(), reset);
    }
}
Also used : ConfigurableBeanFactory(cn.taketoday.beans.factory.config.ConfigurableBeanFactory) BeanDefinition(cn.taketoday.beans.factory.config.BeanDefinition) NoSuchBeanDefinitionException(cn.taketoday.beans.factory.NoSuchBeanDefinitionException) HashSet(java.util.HashSet)

Example 5 with ConfigurableBeanFactory

use of cn.taketoday.beans.factory.config.ConfigurableBeanFactory in project today-infrastructure by TAKETODAY.

the class AbstractApplicationContextRunner method createAndLoadContext.

private C createAndLoadContext() {
    C context = this.runnerConfiguration.contextFactory.get();
    ConfigurableBeanFactory beanFactory = context.getBeanFactory();
    if (beanFactory instanceof AbstractAutowireCapableBeanFactory) {
        ((AbstractAutowireCapableBeanFactory) beanFactory).setAllowCircularReferences(this.runnerConfiguration.allowCircularReferences);
        if (beanFactory instanceof StandardBeanFactory) {
            ((StandardBeanFactory) beanFactory).setAllowBeanDefinitionOverriding(this.runnerConfiguration.allowBeanDefinitionOverriding);
        }
    }
    try {
        configureContext(context);
        return context;
    } catch (RuntimeException ex) {
        context.close();
        throw ex;
    }
}
Also used : ConfigurableBeanFactory(cn.taketoday.beans.factory.config.ConfigurableBeanFactory) AbstractAutowireCapableBeanFactory(cn.taketoday.beans.factory.support.AbstractAutowireCapableBeanFactory) StandardBeanFactory(cn.taketoday.beans.factory.support.StandardBeanFactory)

Aggregations

ConfigurableBeanFactory (cn.taketoday.beans.factory.config.ConfigurableBeanFactory)36 Test (org.junit.jupiter.api.Test)15 BeanDefinitionRegistry (cn.taketoday.beans.factory.support.BeanDefinitionRegistry)7 BeanInstantiationException (cn.taketoday.beans.BeanInstantiationException)5 RootBeanDefinition (cn.taketoday.beans.factory.support.RootBeanDefinition)5 Environment (cn.taketoday.core.env.Environment)5 BeanDefinition (cn.taketoday.beans.factory.config.BeanDefinition)4 AbstractApplicationContext (cn.taketoday.context.support.AbstractApplicationContext)4 TestBean (cn.taketoday.beans.testfixture.beans.TestBean)3 CachedIntrospectionResults (cn.taketoday.beans.CachedIntrospectionResults)2 BeanCreationException (cn.taketoday.beans.factory.BeanCreationException)2 BeanCurrentlyInCreationException (cn.taketoday.beans.factory.BeanCurrentlyInCreationException)2 NoSuchBeanDefinitionException (cn.taketoday.beans.factory.NoSuchBeanDefinitionException)2 ObjectProvider (cn.taketoday.beans.factory.ObjectProvider)2 UnsatisfiedDependencyException (cn.taketoday.beans.factory.UnsatisfiedDependencyException)2 Autowired (cn.taketoday.beans.factory.annotation.Autowired)2 Scope (cn.taketoday.beans.factory.config.Scope)2 AbstractAutowireCapableBeanFactory (cn.taketoday.beans.factory.support.AbstractAutowireCapableBeanFactory)2 BeanDefinitionOverrideException (cn.taketoday.beans.factory.support.BeanDefinitionOverrideException)2 BeanNameGenerator (cn.taketoday.beans.factory.support.BeanNameGenerator)2