org.springframework.context.annotation.AnnotationConfigApplicationContext

Here are the examples of the java api org.springframework.context.annotation.AnnotationConfigApplicationContext taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1339 Examples 7

19 View Source File : Application.java
License : GNU General Public License v3.0
Project Creator : zhonghuasheng

public static void main(String[] args) {
    AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfig.clreplaced);
    while (true) {
    }
/**
 * FixedRate: 15:29:49
 * FixedDelay: 15:29:49
 * Cron: 15:29:51
 * FixedDelay: 15:29:51
 * FixedDelay: 15:29:53
 * Cron: 15:29:54
 * FixedRate: 15:29:54
 * FixedDelay: 15:29:55
 * Cron: 15:29:57
 * FixedDelay: 15:29:57
 * FixedRate: 15:29:59
 * FixedDelay: 15:29:59
 */
}

19 View Source File : SamplePropertyValidationApplicationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link SamplePropertyValidationApplication}.
 *
 * @author Lucas Saldanha
 * @author Stephane Nicoll
 */
public clreplaced SamplePropertyValidationApplicationTests {

    private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    @After
    public void closeContext() {
        this.context.close();
    }

    @Test
    public void bindValidProperties() {
        this.context.register(SamplePropertyValidationApplication.clreplaced);
        TestPropertyValues.of("sample.host:192.168.0.1", "sample.port:9090").applyTo(this.context);
        this.context.refresh();
        SampleProperties properties = this.context.getBean(SampleProperties.clreplaced);
        replacedertThat(properties.getHost()).isEqualTo("192.168.0.1");
        replacedertThat(properties.getPort()).isEqualTo(Integer.valueOf(9090));
    }

    @Test
    public void bindInvalidHost() {
        this.context.register(SamplePropertyValidationApplication.clreplaced);
        TestPropertyValues.of("sample.host:xxxxxx", "sample.port:9090").applyTo(this.context);
        replacedertThatExceptionOfType(BeanCreationException.clreplaced).isThrownBy(() -> this.context.refresh()).withMessageContaining("Failed to bind properties under 'sample'");
    }

    @Test
    public void bindNullHost() {
        this.context.register(SamplePropertyValidationApplication.clreplaced);
        replacedertThatExceptionOfType(BeanCreationException.clreplaced).isThrownBy(() -> this.context.refresh()).withMessageContaining("Failed to bind properties under 'sample'");
    }

    @Test
    public void validatorOnlyCalledOnSupportedClreplaced() {
        this.context.register(SamplePropertyValidationApplication.clreplaced);
        // our validator will not apply
        this.context.register(ServerProperties.clreplaced);
        TestPropertyValues.of("sample.host:192.168.0.1", "sample.port:9090").applyTo(this.context);
        this.context.refresh();
        SampleProperties properties = this.context.getBean(SampleProperties.clreplaced);
        replacedertThat(properties.getHost()).isEqualTo("192.168.0.1");
        replacedertThat(properties.getPort()).isEqualTo(Integer.valueOf(9090));
    }
}

protected final ConfigurableApplicationContext createContext(String driverClreplacedName, String url, Clreplaced<?>... clreplacedes) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.register(clreplacedes);
    context.register(DevToolsDataSourceAutoConfiguration.clreplaced);
    if (driverClreplacedName != null) {
        TestPropertyValues.of("spring.datasource.driver-clreplaced-name:" + driverClreplacedName).applyTo(context);
    }
    if (url != null) {
        TestPropertyValues.of("spring.datasource.url:" + url).applyTo(context);
    }
    context.refresh();
    return context;
}

19 View Source File : ConditionalOnEnabledResourceChainTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link ConditionalOnEnabledResourceChain}.
 *
 * @author Stephane Nicoll
 */
public clreplaced ConditionalOnEnabledResourceChainTests {

    private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    @After
    public void closeContext() {
        this.context.close();
    }

    @Test
    public void disabledByDefault() {
        load();
        replacedertThat(this.context.containsBean("foo")).isFalse();
    }

    @Test
    public void disabledExplicitly() {
        load("spring.resources.chain.enabled:false");
        replacedertThat(this.context.containsBean("foo")).isFalse();
    }

    @Test
    public void enabledViaMainEnabledFlag() {
        load("spring.resources.chain.enabled:true");
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    @Test
    public void enabledViaFixedStrategyFlag() {
        load("spring.resources.chain.strategy.fixed.enabled:true");
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    @Test
    public void enabledViaContentStrategyFlag() {
        load("spring.resources.chain.strategy.content.enabled:true");
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    private void load(String... environment) {
        this.context.register(Config.clreplaced);
        TestPropertyValues.of(environment).applyTo(this.context);
        this.context.refresh();
    }

    @Configuration
    static clreplaced Config {

        @Bean
        @ConditionalOnEnabledResourceChain
        public String foo() {
            return "foo";
        }
    }
}

19 View Source File : RestTemplateAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link RestTemplateAutoConfiguration}
 *
 * @author Stephane Nicoll
 * @author Phillip Webb
 */
public clreplaced RestTemplateAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void restTemplateWhenMessageConvertersDefinedShouldHaveMessageConverters() {
        load(HttpMessageConvertersAutoConfiguration.clreplaced, RestTemplateConfig.clreplaced);
        replacedertThat(this.context.getBeansOfType(RestTemplate.clreplaced)).hreplacedize(1);
        RestTemplate restTemplate = this.context.getBean(RestTemplate.clreplaced);
        List<HttpMessageConverter<?>> converters = this.context.getBean(HttpMessageConverters.clreplaced).getConverters();
        replacedertThat(restTemplate.getMessageConverters()).containsExactlyElementsOf(converters);
        replacedertThat(restTemplate.getRequestFactory()).isInstanceOf(HttpComponentsClientHttpRequestFactory.clreplaced);
    }

    @Test
    public void restTemplateWhenNoMessageConvertersDefinedShouldHaveDefaultMessageConverters() {
        load(RestTemplateConfig.clreplaced);
        RestTemplate restTemplate = this.context.getBean(RestTemplate.clreplaced);
        replacedertThat(restTemplate.getMessageConverters().size()).isEqualTo(new RestTemplate().getMessageConverters().size());
    }

    @Test
    public void restTemplateWhenHasCustomMessageConvertersShouldHaveMessageConverters() {
        load(CustomHttpMessageConverter.clreplaced, HttpMessageConvertersAutoConfiguration.clreplaced, RestTemplateConfig.clreplaced);
        RestTemplate restTemplate = this.context.getBean(RestTemplate.clreplaced);
        List<Clreplaced<?>> converterClreplacedes = new ArrayList<>();
        for (HttpMessageConverter<?> converter : restTemplate.getMessageConverters()) {
            converterClreplacedes.add(converter.getClreplaced());
        }
        replacedertThat(converterClreplacedes).contains(CustomHttpMessageConverter.clreplaced);
    }

    @Test
    public void restTemplateWhenHasCustomBuilderShouldUseCustomBuilder() {
        load(RestTemplateConfig.clreplaced, CustomRestTemplateBuilderConfig.clreplaced);
        replacedertThat(this.context.getBeansOfType(RestTemplate.clreplaced)).hreplacedize(1);
        RestTemplate restTemplate = this.context.getBean(RestTemplate.clreplaced);
        replacedertThat(restTemplate.getMessageConverters()).hreplacedize(1);
        replacedertThat(restTemplate.getMessageConverters().get(0)).isInstanceOf(CustomHttpMessageConverter.clreplaced);
    }

    @Test
    public void restTemplateShouldApplyCustomizer() {
        load(RestTemplateCustomizerConfig.clreplaced, RestTemplateConfig.clreplaced);
        RestTemplate restTemplate = this.context.getBean(RestTemplate.clreplaced);
        RestTemplateCustomizer customizer = this.context.getBean(RestTemplateCustomizer.clreplaced);
        verify(customizer).customize(restTemplate);
    }

    @Test
    public void builderShouldBeFreshForEachUse() {
        load(DirtyRestTemplateConfig.clreplaced);
    }

    public void load(Clreplaced<?>... config) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.register(config);
        ctx.register(RestTemplateAutoConfiguration.clreplaced);
        ctx.refresh();
        this.context = ctx;
    }

    @Configuration
    static clreplaced RestTemplateConfig {

        @Bean
        public RestTemplate restTemplate(RestTemplateBuilder builder) {
            return builder.build();
        }
    }

    @Configuration
    static clreplaced DirtyRestTemplateConfig {

        @Bean
        public RestTemplate restTemplateOne(RestTemplateBuilder builder) {
            try {
                return builder.build();
            } finally {
                breakBuilderOnNextCall(builder);
            }
        }

        @Bean
        public RestTemplate restTemplateTwo(RestTemplateBuilder builder) {
            try {
                return builder.build();
            } finally {
                breakBuilderOnNextCall(builder);
            }
        }

        private void breakBuilderOnNextCall(RestTemplateBuilder builder) {
            builder.additionalCustomizers((restTemplate) -> {
                throw new IllegalStateException();
            });
        }
    }

    @Configuration
    static clreplaced CustomRestTemplateBuilderConfig {

        @Bean
        public RestTemplateBuilder restTemplateBuilder() {
            return new RestTemplateBuilder().messageConverters(new CustomHttpMessageConverter());
        }
    }

    @Configuration
    static clreplaced RestTemplateCustomizerConfig {

        @Bean
        public RestTemplateCustomizer restTemplateCustomizer() {
            return mock(RestTemplateCustomizer.clreplaced);
        }
    }

    static clreplaced CustomHttpMessageConverter extends StringHttpMessageConverter {
    }
}

19 View Source File : RestTemplateAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

public void load(Clreplaced<?>... config) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(config);
    ctx.register(RestTemplateAutoConfiguration.clreplaced);
    ctx.refresh();
    this.context = ctx;
}

19 View Source File : ValidatorAdapterTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link ValidatorAdapter}.
 *
 * @author Stephane Nicoll
 */
public clreplaced ValidatorAdapterTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void wrapLocalValidatorFactoryBean() {
        ValidatorAdapter wrapper = load(LocalValidatorFactoryBeanConfig.clreplaced);
        replacedertThat(wrapper.supports(SampleData.clreplaced)).isTrue();
        MapBindingResult errors = new MapBindingResult(new HashMap<String, Object>(), "test");
        wrapper.validate(new SampleData(40), errors);
        replacedertThat(errors.getErrorCount()).isEqualTo(1);
    }

    @Test
    public void wrapperInvokesCallbackOnNonManagedBean() {
        load(NonManagedBeanConfig.clreplaced);
        LocalValidatorFactoryBean validator = this.context.getBean(NonManagedBeanConfig.clreplaced).validator;
        verify(validator, times(1)).setApplicationContext(any(ApplicationContext.clreplaced));
        verify(validator, times(1)).afterPropertiesSet();
        verify(validator, never()).destroy();
        this.context.close();
        this.context = null;
        verify(validator, times(1)).destroy();
    }

    @Test
    public void wrapperDoesNotInvokeCallbackOnManagedBean() {
        load(ManagedBeanConfig.clreplaced);
        LocalValidatorFactoryBean validator = this.context.getBean(ManagedBeanConfig.clreplaced).validator;
        verify(validator, never()).setApplicationContext(any(ApplicationContext.clreplaced));
        verify(validator, never()).afterPropertiesSet();
        verify(validator, never()).destroy();
        this.context.close();
        this.context = null;
        verify(validator, never()).destroy();
    }

    private ValidatorAdapter load(Clreplaced<?> config) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.register(config);
        ctx.refresh();
        this.context = ctx;
        return this.context.getBean(ValidatorAdapter.clreplaced);
    }

    @Configuration
    static clreplaced LocalValidatorFactoryBeanConfig {

        @Bean
        public LocalValidatorFactoryBean validator() {
            return new LocalValidatorFactoryBean();
        }

        @Bean
        public ValidatorAdapter wrapper() {
            return new ValidatorAdapter(validator(), true);
        }
    }

    @Configuration
    static clreplaced NonManagedBeanConfig {

        private final LocalValidatorFactoryBean validator = mock(LocalValidatorFactoryBean.clreplaced);

        @Bean
        public ValidatorAdapter wrapper() {
            return new ValidatorAdapter(this.validator, false);
        }
    }

    @Configuration
    static clreplaced ManagedBeanConfig {

        private final LocalValidatorFactoryBean validator = mock(LocalValidatorFactoryBean.clreplaced);

        @Bean
        public ValidatorAdapter wrapper() {
            return new ValidatorAdapter(this.validator, true);
        }
    }

    static clreplaced SampleData {

        @Min(42)
        private int counter;

        SampleData(int counter) {
            this.counter = counter;
        }
    }
}

19 View Source File : ValidationAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link ValidationAutoConfiguration}.
 *
 * @author Stephane Nicoll
 * @author Phillip Webb
 */
public clreplaced ValidationAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void validationAutoConfigurationShouldConfigureDefaultValidator() {
        load(Config.clreplaced);
        String[] jsrValidatorNames = this.context.getBeanNamesForType(Validator.clreplaced);
        String[] springValidatorNames = this.context.getBeanNamesForType(org.springframework.validation.Validator.clreplaced);
        replacedertThat(jsrValidatorNames).containsExactly("defaultValidator");
        replacedertThat(springValidatorNames).containsExactly("defaultValidator");
        Validator jsrValidator = this.context.getBean(Validator.clreplaced);
        org.springframework.validation.Validator springValidator = this.context.getBean(org.springframework.validation.Validator.clreplaced);
        replacedertThat(jsrValidator).isInstanceOf(LocalValidatorFactoryBean.clreplaced);
        replacedertThat(jsrValidator).isEqualTo(springValidator);
        replacedertThat(isPrimaryBean("defaultValidator")).isTrue();
    }

    @Test
    public void validationAutoConfigurationWhenUserProvidesValidatorShouldBackOff() {
        load(UserDefinedValidatorConfig.clreplaced);
        String[] jsrValidatorNames = this.context.getBeanNamesForType(Validator.clreplaced);
        String[] springValidatorNames = this.context.getBeanNamesForType(org.springframework.validation.Validator.clreplaced);
        replacedertThat(jsrValidatorNames).containsExactly("customValidator");
        replacedertThat(springValidatorNames).containsExactly("customValidator");
        org.springframework.validation.Validator springValidator = this.context.getBean(org.springframework.validation.Validator.clreplaced);
        Validator jsrValidator = this.context.getBean(Validator.clreplaced);
        replacedertThat(jsrValidator).isInstanceOf(OptionalValidatorFactoryBean.clreplaced);
        replacedertThat(jsrValidator).isEqualTo(springValidator);
        replacedertThat(isPrimaryBean("customValidator")).isFalse();
    }

    @Test
    public void validationAutoConfigurationWhenUserProvidesDefaultValidatorShouldNotEnablePrimary() {
        load(UserDefinedDefaultValidatorConfig.clreplaced);
        String[] jsrValidatorNames = this.context.getBeanNamesForType(Validator.clreplaced);
        String[] springValidatorNames = this.context.getBeanNamesForType(org.springframework.validation.Validator.clreplaced);
        replacedertThat(jsrValidatorNames).containsExactly("defaultValidator");
        replacedertThat(springValidatorNames).containsExactly("defaultValidator");
        replacedertThat(isPrimaryBean("defaultValidator")).isFalse();
    }

    @Test
    public void validationAutoConfigurationWhenUserProvidesJsrValidatorShouldBackOff() {
        load(UserDefinedJsrValidatorConfig.clreplaced);
        String[] jsrValidatorNames = this.context.getBeanNamesForType(Validator.clreplaced);
        String[] springValidatorNames = this.context.getBeanNamesForType(org.springframework.validation.Validator.clreplaced);
        replacedertThat(jsrValidatorNames).containsExactly("customValidator");
        replacedertThat(springValidatorNames).isEmpty();
        replacedertThat(isPrimaryBean("customValidator")).isFalse();
    }

    @Test
    public void validationAutoConfigurationWhenUserProvidesSpringValidatorShouldCreateJsrValidator() {
        load(UserDefinedSpringValidatorConfig.clreplaced);
        String[] jsrValidatorNames = this.context.getBeanNamesForType(Validator.clreplaced);
        String[] springValidatorNames = this.context.getBeanNamesForType(org.springframework.validation.Validator.clreplaced);
        replacedertThat(jsrValidatorNames).containsExactly("defaultValidator");
        replacedertThat(springValidatorNames).containsExactly("customValidator", "anotherCustomValidator", "defaultValidator");
        Validator jsrValidator = this.context.getBean(Validator.clreplaced);
        org.springframework.validation.Validator springValidator = this.context.getBean(org.springframework.validation.Validator.clreplaced);
        replacedertThat(jsrValidator).isInstanceOf(LocalValidatorFactoryBean.clreplaced);
        replacedertThat(jsrValidator).isEqualTo(springValidator);
        replacedertThat(isPrimaryBean("defaultValidator")).isTrue();
    }

    @Test
    public void validationAutoConfigurationWhenUserProvidesPrimarySpringValidatorShouldRemovePrimaryFlag() {
        load(UserDefinedPrimarySpringValidatorConfig.clreplaced);
        String[] jsrValidatorNames = this.context.getBeanNamesForType(Validator.clreplaced);
        String[] springValidatorNames = this.context.getBeanNamesForType(org.springframework.validation.Validator.clreplaced);
        replacedertThat(jsrValidatorNames).containsExactly("defaultValidator");
        replacedertThat(springValidatorNames).containsExactly("customValidator", "anotherCustomValidator", "defaultValidator");
        Validator jsrValidator = this.context.getBean(Validator.clreplaced);
        org.springframework.validation.Validator springValidator = this.context.getBean(org.springframework.validation.Validator.clreplaced);
        replacedertThat(jsrValidator).isInstanceOf(LocalValidatorFactoryBean.clreplaced);
        replacedertThat(springValidator).isEqualTo(this.context.getBean("anotherCustomValidator"));
        replacedertThat(isPrimaryBean("defaultValidator")).isFalse();
    }

    @Test
    public void validationIsEnabled() {
        load(SampleService.clreplaced);
        replacedertThat(this.context.getBeansOfType(Validator.clreplaced)).hreplacedize(1);
        SampleService service = this.context.getBean(SampleService.clreplaced);
        service.doSomething("Valid");
        replacedertThatExceptionOfType(ConstraintViolationException.clreplaced).isThrownBy(() -> service.doSomething("KO"));
    }

    @Test
    public void validationUsesCglibProxy() {
        load(DefaultAnotherSampleService.clreplaced);
        replacedertThat(this.context.getBeansOfType(Validator.clreplaced)).hreplacedize(1);
        DefaultAnotherSampleService service = this.context.getBean(DefaultAnotherSampleService.clreplaced);
        service.doSomething(42);
        replacedertThatExceptionOfType(ConstraintViolationException.clreplaced).isThrownBy(() -> service.doSomething(2));
    }

    @Test
    public void validationCanBeConfiguredToUseJdkProxy() {
        load(AnotherSampleServiceConfiguration.clreplaced, "spring.aop.proxy-target-clreplaced=false");
        replacedertThat(this.context.getBeansOfType(Validator.clreplaced)).hreplacedize(1);
        replacedertThat(this.context.getBeansOfType(DefaultAnotherSampleService.clreplaced)).isEmpty();
        AnotherSampleService service = this.context.getBean(AnotherSampleService.clreplaced);
        service.doSomething(42);
        replacedertThatExceptionOfType(ConstraintViolationException.clreplaced).isThrownBy(() -> service.doSomething(2));
    }

    @Test
    public void userDefinedMethodValidationPostProcessorTakesPrecedence() {
        load(SampleConfiguration.clreplaced);
        replacedertThat(this.context.getBeansOfType(Validator.clreplaced)).hreplacedize(1);
        Object userMethodValidationPostProcessor = this.context.getBean("testMethodValidationPostProcessor");
        replacedertThat(this.context.getBean(MethodValidationPostProcessor.clreplaced)).isSameAs(userMethodValidationPostProcessor);
        replacedertThat(this.context.getBeansOfType(MethodValidationPostProcessor.clreplaced)).hreplacedize(1);
        replacedertThat(this.context.getBean(Validator.clreplaced)).isNotSameAs(new DirectFieldAccessor(userMethodValidationPostProcessor).getPropertyValue("validator"));
    }

    @Test
    public void methodValidationPostProcessorValidatorDependencyDoesNotTriggerEarlyInitialization() {
        load(CustomValidatorConfiguration.clreplaced);
        replacedertThat(this.context.getBean(TestBeanPostProcessor.clreplaced).postProcessed).contains("someService");
    }

    private boolean isPrimaryBean(String beanName) {
        return this.context.getBeanDefinition(beanName).isPrimary();
    }

    private void load(Clreplaced<?> config, String... environment) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        TestPropertyValues.of(environment).applyTo(ctx);
        if (config != null) {
            ctx.register(config);
        }
        ctx.register(ValidationAutoConfiguration.clreplaced);
        ctx.refresh();
        this.context = ctx;
    }

    @Configuration
    static clreplaced Config {
    }

    @Configuration
    static clreplaced UserDefinedValidatorConfig {

        @Bean
        public OptionalValidatorFactoryBean customValidator() {
            return new OptionalValidatorFactoryBean();
        }
    }

    @Configuration
    static clreplaced UserDefinedDefaultValidatorConfig {

        @Bean
        public OptionalValidatorFactoryBean defaultValidator() {
            return new OptionalValidatorFactoryBean();
        }
    }

    @Configuration
    static clreplaced UserDefinedJsrValidatorConfig {

        @Bean
        public Validator customValidator() {
            return mock(Validator.clreplaced);
        }
    }

    @Configuration
    static clreplaced UserDefinedSpringValidatorConfig {

        @Bean
        public org.springframework.validation.Validator customValidator() {
            return mock(org.springframework.validation.Validator.clreplaced);
        }

        @Bean
        public org.springframework.validation.Validator anotherCustomValidator() {
            return mock(org.springframework.validation.Validator.clreplaced);
        }
    }

    @Configuration
    static clreplaced UserDefinedPrimarySpringValidatorConfig {

        @Bean
        public org.springframework.validation.Validator customValidator() {
            return mock(org.springframework.validation.Validator.clreplaced);
        }

        @Bean
        @Primary
        public org.springframework.validation.Validator anotherCustomValidator() {
            return mock(org.springframework.validation.Validator.clreplaced);
        }
    }

    @Validated
    static clreplaced SampleService {

        public void doSomething(@Size(min = 3, max = 10) String name) {
        }
    }

    interface AnotherSampleService {

        void doSomething(@Min(42) Integer counter);
    }

    @Validated
    static clreplaced DefaultAnotherSampleService implements AnotherSampleService {

        @Override
        public void doSomething(Integer counter) {
        }
    }

    @Configuration
    static clreplaced AnotherSampleServiceConfiguration {

        @Bean
        public AnotherSampleService anotherSampleService() {
            return new DefaultAnotherSampleService();
        }
    }

    @Configuration
    static clreplaced SampleConfiguration {

        @Bean
        public MethodValidationPostProcessor testMethodValidationPostProcessor() {
            return new MethodValidationPostProcessor();
        }
    }

    @org.springframework.context.annotation.Configuration
    static clreplaced CustomValidatorConfiguration {

        CustomValidatorConfiguration(SomeService someService) {
        }

        @Bean
        Validator customValidator() {
            return new CustomValidatorBean();
        }

        @Bean
        static TestBeanPostProcessor testBeanPostProcessor() {
            return new TestBeanPostProcessor();
        }

        @Configuration
        static clreplaced SomeServiceConfiguration {

            @Bean
            public SomeService someService() {
                return new SomeService();
            }
        }

        static clreplaced SomeService {
        }

        static clreplaced TestBeanPostProcessor implements BeanPostProcessor {

            private Set<String> postProcessed = new HashSet<>();

            @Override
            public Object postProcessAfterInitialization(Object bean, String name) {
                this.postProcessed.add(name);
                return bean;
            }

            @Override
            public Object postProcessBeforeInitialization(Object bean, String name) {
                return bean;
            }
        }
    }
}

19 View Source File : TransactionAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link TransactionAutoConfiguration}.
 *
 * @author Stephane Nicoll
 * @author Phillip Webb
 */
public clreplaced TransactionAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void tearDown() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void noTransactionManager() {
        load(EmptyConfiguration.clreplaced);
        replacedertThat(this.context.getBeansOfType(TransactionTemplate.clreplaced)).isEmpty();
    }

    @Test
    public void singleTransactionManager() {
        load(new Clreplaced<?>[] { DataSourceAutoConfiguration.clreplaced, DataSourceTransactionManagerAutoConfiguration.clreplaced }, "spring.datasource.initialization-mode:never");
        PlatformTransactionManager transactionManager = this.context.getBean(PlatformTransactionManager.clreplaced);
        TransactionTemplate transactionTemplate = this.context.getBean(TransactionTemplate.clreplaced);
        replacedertThat(transactionTemplate.getTransactionManager()).isSameAs(transactionManager);
    }

    @Test
    public void severalTransactionManagers() {
        load(SeveralTransactionManagersConfiguration.clreplaced);
        replacedertThat(this.context.getBeansOfType(TransactionTemplate.clreplaced)).isEmpty();
    }

    @Test
    public void customTransactionManager() {
        load(CustomTransactionManagerConfiguration.clreplaced);
        Map<String, TransactionTemplate> beans = this.context.getBeansOfType(TransactionTemplate.clreplaced);
        replacedertThat(beans).hreplacedize(1);
        replacedertThat(beans.containsKey("transactionTemplateFoo")).isTrue();
    }

    @Test
    public void platformTransactionManagerCustomizers() {
        load(SeveralTransactionManagersConfiguration.clreplaced);
        TransactionManagerCustomizers customizers = this.context.getBean(TransactionManagerCustomizers.clreplaced);
        List<?> field = (List<?>) ReflectionTestUtils.getField(customizers, "customizers");
        replacedertThat(field).hreplacedize(1).first().isInstanceOf(TransactionProperties.clreplaced);
    }

    @Test
    public void transactionNotManagedWithNoTransactionManager() {
        load(BaseConfiguration.clreplaced);
        replacedertThat(this.context.getBean(TransactionalService.clreplaced).isTransactionActive()).isFalse();
    }

    @Test
    public void transactionManagerUsesCglibByDefault() {
        load(TransactionManagersConfiguration.clreplaced);
        replacedertThat(this.context.getBean(AnotherServiceImpl.clreplaced).isTransactionActive()).isTrue();
        replacedertThat(this.context.getBeansOfType(TransactionalServiceImpl.clreplaced)).hreplacedize(1);
    }

    @Test
    public void transactionManagerCanBeConfiguredToJdkProxy() {
        load(TransactionManagersConfiguration.clreplaced, "spring.aop.proxy-target-clreplaced=false");
        replacedertThat(this.context.getBean(AnotherService.clreplaced).isTransactionActive()).isTrue();
        replacedertThat(this.context.getBeansOfType(AnotherServiceImpl.clreplaced)).hreplacedize(0);
        replacedertThat(this.context.getBeansOfType(TransactionalServiceImpl.clreplaced)).hreplacedize(0);
    }

    @Test
    public void customEnableTransactionManagementTakesPrecedence() {
        load(new Clreplaced<?>[] { CustomTransactionManagementConfiguration.clreplaced, TransactionManagersConfiguration.clreplaced }, "spring.aop.proxy-target-clreplaced=true");
        replacedertThat(this.context.getBean(AnotherService.clreplaced).isTransactionActive()).isTrue();
        replacedertThat(this.context.getBeansOfType(AnotherServiceImpl.clreplaced)).hreplacedize(0);
        replacedertThat(this.context.getBeansOfType(TransactionalServiceImpl.clreplaced)).hreplacedize(0);
    }

    private void load(Clreplaced<?> config, String... environment) {
        load(new Clreplaced<?>[] { config }, environment);
    }

    private void load(Clreplaced<?>[] configs, String... environment) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(configs);
        applicationContext.register(TransactionAutoConfiguration.clreplaced);
        TestPropertyValues.of(environment).applyTo(applicationContext);
        applicationContext.refresh();
        this.context = applicationContext;
    }

    @Configuration
    static clreplaced EmptyConfiguration {
    }

    @Configuration
    static clreplaced SeveralTransactionManagersConfiguration {

        @Bean
        public PlatformTransactionManager transactionManagerOne() {
            return mock(PlatformTransactionManager.clreplaced);
        }

        @Bean
        public PlatformTransactionManager transactionManagerTwo() {
            return mock(PlatformTransactionManager.clreplaced);
        }
    }

    @Configuration
    static clreplaced CustomTransactionManagerConfiguration {

        @Bean
        public TransactionTemplate transactionTemplateFoo() {
            return new TransactionTemplate(transactionManagerFoo());
        }

        @Bean
        public PlatformTransactionManager transactionManagerFoo() {
            return mock(PlatformTransactionManager.clreplaced);
        }
    }

    @Configuration
    static clreplaced BaseConfiguration {

        @Bean
        public TransactionalService transactionalService() {
            return new TransactionalServiceImpl();
        }

        @Bean
        public AnotherServiceImpl anotherService() {
            return new AnotherServiceImpl();
        }
    }

    @Configuration
    @Import(BaseConfiguration.clreplaced)
    static clreplaced TransactionManagersConfiguration {

        @Bean
        public DataSourceTransactionManager transactionManager() {
            return new DataSourceTransactionManager(dataSource());
        }

        @Bean
        public DataSource dataSource() {
            return DataSourceBuilder.create().driverClreplacedName("org.hsqldb.jdbc.JDBCDriver").url("jdbc:hsqldb:mem:tx").username("sa").build();
        }
    }

    @Configuration
    @EnableTransactionManagement(proxyTargetClreplaced = false)
    static clreplaced CustomTransactionManagementConfiguration {
    }

    interface TransactionalService {

        @Transactional
        boolean isTransactionActive();
    }

    static clreplaced TransactionalServiceImpl implements TransactionalService {

        @Override
        public boolean isTransactionActive() {
            return TransactionSynchronizationManager.isActualTransactionActive();
        }
    }

    interface AnotherService {

        boolean isTransactionActive();
    }

    static clreplaced AnotherServiceImpl implements AnotherService {

        @Override
        @Transactional
        public boolean isTransactionActive() {
            return TransactionSynchronizationManager.isActualTransactionActive();
        }
    }
}

19 View Source File : JtaAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link JtaAutoConfiguration}.
 *
 * @author Josh Long
 * @author Phillip Webb
 * @author Andy Wilkinson
 * @author Kazuki Shimizu
 */
public clreplaced JtaAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @Before
    public void cleanUpLogs() {
        FileSystemUtils.deleteRecursively(new File("target/transaction-logs"));
    }

    @After
    public void closeContext() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void customPlatformTransactionManager() {
        this.context = new AnnotationConfigApplicationContext(CustomTransactionManagerConfig.clreplaced, JtaAutoConfiguration.clreplaced);
        replacedertThatExceptionOfType(NoSuchBeanDefinitionException.clreplaced).isThrownBy(() -> this.context.getBean(JtaTransactionManager.clreplaced));
    }

    @Test
    public void disableJtaSupport() {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.jta.enabled:false").applyTo(this.context);
        this.context.register(JtaAutoConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBeansOfType(JtaTransactionManager.clreplaced)).isEmpty();
        replacedertThat(this.context.getBeansOfType(XADataSourceWrapper.clreplaced)).isEmpty();
        replacedertThat(this.context.getBeansOfType(XAConnectionFactoryWrapper.clreplaced)).isEmpty();
    }

    @Test
    public void atomikosSanityCheck() {
        this.context = new AnnotationConfigApplicationContext(JtaProperties.clreplaced, AtomikosJtaConfiguration.clreplaced);
        this.context.getBean(AtomikosProperties.clreplaced);
        this.context.getBean(UserTransactionService.clreplaced);
        this.context.getBean(UserTransactionManager.clreplaced);
        this.context.getBean(UserTransaction.clreplaced);
        this.context.getBean(XADataSourceWrapper.clreplaced);
        this.context.getBean(XAConnectionFactoryWrapper.clreplaced);
        this.context.getBean(AtomikosDependsOnBeanFactoryPostProcessor.clreplaced);
        this.context.getBean(JtaTransactionManager.clreplaced);
    }

    @Test
    public void bitronixSanityCheck() {
        this.context = new AnnotationConfigApplicationContext(JtaProperties.clreplaced, BitronixJtaConfiguration.clreplaced);
        this.context.getBean(bitronix.tm.Configuration.clreplaced);
        this.context.getBean(TransactionManager.clreplaced);
        this.context.getBean(XADataSourceWrapper.clreplaced);
        this.context.getBean(XAConnectionFactoryWrapper.clreplaced);
        this.context.getBean(BitronixDependentBeanFactoryPostProcessor.clreplaced);
        this.context.getBean(JtaTransactionManager.clreplaced);
    }

    @Test
    public void defaultBitronixServerId() throws UnknownHostException {
        this.context = new AnnotationConfigApplicationContext(JtaPropertiesConfiguration.clreplaced, BitronixJtaConfiguration.clreplaced);
        String serverId = this.context.getBean(bitronix.tm.Configuration.clreplaced).getServerId();
        replacedertThat(serverId).isEqualTo(InetAddress.getLocalHost().getHostAddress());
    }

    @Test
    public void customBitronixServerId() {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.jta.transactionManagerId:custom").applyTo(this.context);
        this.context.register(JtaPropertiesConfiguration.clreplaced, BitronixJtaConfiguration.clreplaced);
        this.context.refresh();
        String serverId = this.context.getBean(bitronix.tm.Configuration.clreplaced).getServerId();
        replacedertThat(serverId).isEqualTo("custom");
    }

    @Test
    public void defaultAtomikosTransactionManagerName() {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.jta.logDir:target/transaction-logs").applyTo(this.context);
        this.context.register(JtaPropertiesConfiguration.clreplaced, AtomikosJtaConfiguration.clreplaced);
        this.context.refresh();
        File epochFile = new File("target/transaction-logs/tmlog0.log");
        replacedertThat(epochFile.isFile()).isTrue();
    }

    @Test
    public void atomikosConnectionFactoryPoolConfiguration() {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.jta.atomikos.connectionfactory.minPoolSize:5", "spring.jta.atomikos.connectionfactory.maxPoolSize:10").applyTo(this.context);
        this.context.register(JtaPropertiesConfiguration.clreplaced, AtomikosJtaConfiguration.clreplaced, PoolConfiguration.clreplaced);
        this.context.refresh();
        AtomikosConnectionFactoryBean connectionFactory = this.context.getBean(AtomikosConnectionFactoryBean.clreplaced);
        replacedertThat(connectionFactory.getMinPoolSize()).isEqualTo(5);
        replacedertThat(connectionFactory.getMaxPoolSize()).isEqualTo(10);
    }

    @Test
    public void bitronixConnectionFactoryPoolConfiguration() {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.jta.bitronix.connectionfactory.minPoolSize:5", "spring.jta.bitronix.connectionfactory.maxPoolSize:10").applyTo(this.context);
        this.context.register(JtaPropertiesConfiguration.clreplaced, BitronixJtaConfiguration.clreplaced, PoolConfiguration.clreplaced);
        this.context.refresh();
        PoolingConnectionFactoryBean connectionFactory = this.context.getBean(PoolingConnectionFactoryBean.clreplaced);
        replacedertThat(connectionFactory.getMinPoolSize()).isEqualTo(5);
        replacedertThat(connectionFactory.getMaxPoolSize()).isEqualTo(10);
    }

    @Test
    public void atomikosDataSourcePoolConfiguration() {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.jta.atomikos.datasource.minPoolSize:5", "spring.jta.atomikos.datasource.maxPoolSize:10").applyTo(this.context);
        this.context.register(JtaPropertiesConfiguration.clreplaced, AtomikosJtaConfiguration.clreplaced, PoolConfiguration.clreplaced);
        this.context.refresh();
        AtomikosDataSourceBean dataSource = this.context.getBean(AtomikosDataSourceBean.clreplaced);
        replacedertThat(dataSource.getMinPoolSize()).isEqualTo(5);
        replacedertThat(dataSource.getMaxPoolSize()).isEqualTo(10);
    }

    @Test
    public void bitronixDataSourcePoolConfiguration() {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.jta.bitronix.datasource.minPoolSize:5", "spring.jta.bitronix.datasource.maxPoolSize:10").applyTo(this.context);
        this.context.register(JtaPropertiesConfiguration.clreplaced, BitronixJtaConfiguration.clreplaced, PoolConfiguration.clreplaced);
        this.context.refresh();
        PoolingDataSourceBean dataSource = this.context.getBean(PoolingDataSourceBean.clreplaced);
        replacedertThat(dataSource.getMinPoolSize()).isEqualTo(5);
        replacedertThat(dataSource.getMaxPoolSize()).isEqualTo(10);
    }

    @Test
    public void atomikosCustomizeJtaTransactionManagerUsingProperties() {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true").applyTo(this.context);
        this.context.register(AtomikosJtaConfiguration.clreplaced, TransactionAutoConfiguration.clreplaced);
        this.context.refresh();
        JtaTransactionManager transactionManager = this.context.getBean(JtaTransactionManager.clreplaced);
        replacedertThat(transactionManager.getDefaultTimeout()).isEqualTo(30);
        replacedertThat(transactionManager.isRollbackOnCommitFailure()).isTrue();
    }

    @Test
    public void bitronixCustomizeJtaTransactionManagerUsingProperties() {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true").applyTo(this.context);
        this.context.register(BitronixJtaConfiguration.clreplaced, TransactionAutoConfiguration.clreplaced);
        this.context.refresh();
        JtaTransactionManager transactionManager = this.context.getBean(JtaTransactionManager.clreplaced);
        replacedertThat(transactionManager.getDefaultTimeout()).isEqualTo(30);
        replacedertThat(transactionManager.isRollbackOnCommitFailure()).isTrue();
    }

    @Configuration
    @EnableConfigurationProperties(JtaProperties.clreplaced)
    public static clreplaced JtaPropertiesConfiguration {
    }

    @Configuration
    public static clreplaced CustomTransactionManagerConfig {

        @Bean
        public PlatformTransactionManager transactionManager() {
            return mock(PlatformTransactionManager.clreplaced);
        }
    }

    @Configuration
    public static clreplaced PoolConfiguration {

        @Bean
        public ConnectionFactory pooledConnectionFactory(XAConnectionFactoryWrapper wrapper) throws Exception {
            XAConnectionFactory connectionFactory = mock(XAConnectionFactory.clreplaced);
            XAConnection connection = mock(XAConnection.clreplaced);
            XASession session = mock(XASession.clreplaced);
            TemporaryQueue queue = mock(TemporaryQueue.clreplaced);
            XAResource resource = mock(XAResource.clreplaced);
            given(connectionFactory.createXAConnection()).willReturn(connection);
            given(connection.createXASession()).willReturn(session);
            given(session.createTemporaryQueue()).willReturn(queue);
            given(session.getXAResource()).willReturn(resource);
            return wrapper.wrapConnectionFactory(connectionFactory);
        }

        @Bean
        public DataSource pooledDataSource(XADataSourceWrapper wrapper) throws Exception {
            XADataSource dataSource = mock(XADataSource.clreplaced);
            return wrapper.wrapDataSource(dataSource);
        }
    }
}

19 View Source File : SendGridAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link SendGridAutoConfiguration}.
 *
 * @author Maciej Walkowiak
 * @author Patrick Bray
 */
public clreplaced SendGridAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void expectedSendGridBeanCreatedApiKey() {
        loadContext("spring.sendgrid.api-key:SG.SECRET-API-KEY");
        SendGrid sendGrid = this.context.getBean(SendGrid.clreplaced);
        replacedertThat(sendGrid).extracting("apiKey").containsExactly("SG.SECRET-API-KEY");
    }

    @Test(expected = NoSuchBeanDefinitionException.clreplaced)
    public void autoConfigurationNotFiredWhenPropertiesNotSet() {
        loadContext();
        this.context.getBean(SendGrid.clreplaced);
    }

    @Test
    public void autoConfigurationNotFiredWhenBereplacedreadyCreated() {
        loadContext(ManualSendGridConfiguration.clreplaced, "spring.sendgrid.api-key:SG.SECRET-API-KEY");
        SendGrid sendGrid = this.context.getBean(SendGrid.clreplaced);
        replacedertThat(sendGrid).extracting("apiKey").containsExactly("SG.CUSTOM_API_KEY");
    }

    @Test
    public void expectedSendGridBeanWithProxyCreated() {
        loadContext("spring.sendgrid.api-key:SG.SECRET-API-KEY", "spring.sendgrid.proxy.host:localhost", "spring.sendgrid.proxy.port:5678");
        SendGrid sendGrid = this.context.getBean(SendGrid.clreplaced);
        replacedertThat(sendGrid).extracting("client").extracting("httpClient").extracting("routePlanner").hasOnlyElementsOfType(DefaultProxyRoutePlanner.clreplaced);
    }

    private void loadContext(String... environment) {
        this.loadContext(null, environment);
    }

    private void loadContext(Clreplaced<?> additionalConfiguration, String... environment) {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of(environment).applyTo(this.context);
        ConfigurationPropertySources.attach(this.context.getEnvironment());
        this.context.register(SendGridAutoConfiguration.clreplaced);
        if (additionalConfiguration != null) {
            this.context.register(additionalConfiguration);
        }
        this.context.refresh();
    }

    @Configuration
    static clreplaced ManualSendGridConfiguration {

        @Bean
        SendGrid sendGrid() {
            return new SendGrid("SG.CUSTOM_API_KEY", true);
        }
    }
}

19 View Source File : EmbeddedMongoAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link EmbeddedMongoAutoConfiguration}.
 *
 * @author Henryk Konsek
 * @author Andy Wilkinson
 * @author Stephane Nicoll
 */
public clreplaced EmbeddedMongoAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void defaultVersion() {
        replacedertVersionConfiguration(null, "3.5.5");
    }

    @Test
    public void customVersion() {
        replacedertVersionConfiguration("3.4.15", "3.4.15");
    }

    @Test
    public void customFeatures() {
        EnumSet<Feature> features = EnumSet.of(Feature.TEXT_SEARCH, Feature.SYNC_DELAY, Feature.ONLY_WITH_SSL, Feature.NO_HTTP_INTERFACE_ARG);
        if (isWindows()) {
            features.add(Feature.ONLY_WINDOWS_2008_SERVER);
        }
        load("spring.mongodb.embedded.features=" + String.join(", ", features.stream().map(Feature::name).collect(Collectors.toList())));
        replacedertThat(this.context.getBean(EmbeddedMongoProperties.clreplaced).getFeatures()).containsExactlyElementsOf(features);
    }

    @Test
    public void useRandomPortByDefault() {
        load();
        replacedertThat(this.context.getBeansOfType(MongoClient.clreplaced)).hreplacedize(1);
        MongoClient client = this.context.getBean(MongoClient.clreplaced);
        Integer mongoPort = Integer.valueOf(this.context.getEnvironment().getProperty("local.mongo.port"));
        replacedertThat(client.getAddress().getPort()).isEqualTo(mongoPort);
    }

    @Test
    public void specifyPortToZeroAllocateRandomPort() {
        load("spring.data.mongodb.port=0");
        replacedertThat(this.context.getBeansOfType(MongoClient.clreplaced)).hreplacedize(1);
        MongoClient client = this.context.getBean(MongoClient.clreplaced);
        Integer mongoPort = Integer.valueOf(this.context.getEnvironment().getProperty("local.mongo.port"));
        replacedertThat(client.getAddress().getPort()).isEqualTo(mongoPort);
    }

    @Test
    public void randomlyAllocatedPortIsAvailableWhenCreatingMongoClient() {
        load(MongoClientConfiguration.clreplaced);
        MongoClient client = this.context.getBean(MongoClient.clreplaced);
        Integer mongoPort = Integer.valueOf(this.context.getEnvironment().getProperty("local.mongo.port"));
        replacedertThat(client.getAddress().getPort()).isEqualTo(mongoPort);
    }

    @Test
    public void portIsAvailableInParentContext() {
        try (ConfigurableApplicationContext parent = new AnnotationConfigApplicationContext()) {
            parent.refresh();
            this.context = new AnnotationConfigApplicationContext();
            this.context.setParent(parent);
            this.context.register(EmbeddedMongoAutoConfiguration.clreplaced, MongoClientConfiguration.clreplaced);
            this.context.refresh();
            replacedertThat(parent.getEnvironment().getProperty("local.mongo.port")).isNotNull();
        }
    }

    @Test
    public void defaultStorageConfiguration() {
        load(MongoClientConfiguration.clreplaced);
        Storage replication = this.context.getBean(IMongodConfig.clreplaced).replication();
        replacedertThat(replication.getOplogSize()).isEqualTo(0);
        replacedertThat(replication.getDatabaseDir()).isNull();
        replacedertThat(replication.getReplSetName()).isNull();
    }

    @Test
    public void mongoWritesToCustomDatabaseDir() {
        File customDatabaseDir = new File("target/custom-database-dir");
        FileSystemUtils.deleteRecursively(customDatabaseDir);
        load("spring.mongodb.embedded.storage.databaseDir=" + customDatabaseDir.getPath());
        replacedertThat(customDatabaseDir).isDirectory();
        replacedertThat(customDatabaseDir.listFiles()).isNotEmpty();
    }

    @Test
    public void customOpLogSizeIsAppliedToConfiguration() {
        load("spring.mongodb.embedded.storage.oplogSize=1024KB");
        replacedertThat(this.context.getBean(IMongodConfig.clreplaced).replication().getOplogSize()).isEqualTo(1);
    }

    @Test
    public void customOpLogSizeUsesMegabytesPerDefault() {
        load("spring.mongodb.embedded.storage.oplogSize=10");
        replacedertThat(this.context.getBean(IMongodConfig.clreplaced).replication().getOplogSize()).isEqualTo(10);
    }

    @Test
    public void customReplicaSetNameIsAppliedToConfiguration() {
        load("spring.mongodb.embedded.storage.replSetName=testing");
        replacedertThat(this.context.getBean(IMongodConfig.clreplaced).replication().getReplSetName()).isEqualTo("testing");
    }

    private void replacedertVersionConfiguration(String configuredVersion, String expectedVersion) {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.data.mongodb.port=0").applyTo(this.context);
        if (configuredVersion != null) {
            TestPropertyValues.of("spring.mongodb.embedded.version=" + configuredVersion).applyTo(this.context);
        }
        this.context.register(MongoAutoConfiguration.clreplaced, MongoDataAutoConfiguration.clreplaced, EmbeddedMongoAutoConfiguration.clreplaced);
        this.context.refresh();
        MongoTemplate mongo = this.context.getBean(MongoTemplate.clreplaced);
        Doreplacedent buildInfo = mongo.executeCommand("{ buildInfo: 1 }");
        replacedertThat(buildInfo.getString("version")).isEqualTo(expectedVersion);
    }

    private void load(String... environment) {
        load(null, environment);
    }

    private void load(Clreplaced<?> config, String... environment) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        if (config != null) {
            ctx.register(config);
        }
        TestPropertyValues.of(environment).applyTo(ctx);
        ctx.register(EmbeddedMongoAutoConfiguration.clreplaced, MongoAutoConfiguration.clreplaced, PropertyPlaceholderAutoConfiguration.clreplaced);
        ctx.refresh();
        this.context = ctx;
    }

    private boolean isWindows() {
        return File.separatorChar == '\\';
    }

    @Configuration
    static clreplaced MongoClientConfiguration {

        @Bean
        public MongoClient mongoClient(@Value("${local.mongo.port}") int port) {
            return new MongoClient("localhost", port);
        }
    }
}

19 View Source File : KafkaAutoConfigurationIntegrationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

private AnnotationConfigApplicationContext doLoad(Clreplaced<?>[] configs, String... environment) {
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
    applicationContext.register(configs);
    applicationContext.register(KafkaAutoConfiguration.clreplaced);
    TestPropertyValues.of(environment).applyTo(applicationContext);
    applicationContext.refresh();
    return applicationContext;
}

19 View Source File : JooqPropertiesTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link JooqProperties}.
 *
 * @author Stephane Nicoll
 */
public clreplaced JooqPropertiesTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void determineSqlDialectNoCheckIfDialectIsSet() throws SQLException {
        JooqProperties properties = load("spring.jooq.sql-dialect=postgres");
        DataSource dataSource = mockStandaloneDataSource();
        SQLDialect sqlDialect = properties.determineSqlDialect(dataSource);
        replacedertThat(sqlDialect).isEqualTo(SQLDialect.POSTGRES);
        verify(dataSource, never()).getConnection();
    }

    @Test
    public void determineSqlDialectWithKnownUrl() {
        JooqProperties properties = load();
        SQLDialect sqlDialect = properties.determineSqlDialect(mockDataSource("jdbc:h2:mem:testdb"));
        replacedertThat(sqlDialect).isEqualTo(SQLDialect.H2);
    }

    @Test
    public void determineSqlDialectWithKnownUrlAndUserConfig() {
        JooqProperties properties = load("spring.jooq.sql-dialect=mysql");
        SQLDialect sqlDialect = properties.determineSqlDialect(mockDataSource("jdbc:h2:mem:testdb"));
        replacedertThat(sqlDialect).isEqualTo(SQLDialect.MYSQL);
    }

    @Test
    public void determineSqlDialectWithUnknownUrl() {
        JooqProperties properties = load();
        SQLDialect sqlDialect = properties.determineSqlDialect(mockDataSource("jdbc:unknown://localhost"));
        replacedertThat(sqlDialect).isEqualTo(SQLDialect.DEFAULT);
    }

    private DataSource mockStandaloneDataSource() throws SQLException {
        DataSource ds = mock(DataSource.clreplaced);
        given(ds.getConnection()).willThrow(SQLException.clreplaced);
        return ds;
    }

    private DataSource mockDataSource(String jdbcUrl) {
        DataSource ds = mock(DataSource.clreplaced);
        try {
            DatabaseMetaData metadata = mock(DatabaseMetaData.clreplaced);
            given(metadata.getURL()).willReturn(jdbcUrl);
            Connection connection = mock(Connection.clreplaced);
            given(connection.getMetaData()).willReturn(metadata);
            given(ds.getConnection()).willReturn(connection);
        } catch (SQLException ex) {
        // Do nothing
        }
        return ds;
    }

    private JooqProperties load(String... environment) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        TestPropertyValues.of(environment).applyTo(ctx);
        ctx.register(TestConfiguration.clreplaced);
        ctx.refresh();
        this.context = ctx;
        return this.context.getBean(JooqProperties.clreplaced);
    }

    @Configuration
    @EnableConfigurationProperties(JooqProperties.clreplaced)
    static clreplaced TestConfiguration {
    }
}

19 View Source File : JooqPropertiesTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

private JooqProperties load(String... environment) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    TestPropertyValues.of(environment).applyTo(ctx);
    ctx.register(TestConfiguration.clreplaced);
    ctx.refresh();
    this.context = ctx;
    return this.context.getBean(JooqProperties.clreplaced);
}

19 View Source File : JmxAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link JmxAutoConfiguration}.
 *
 * @author Christian Dupuis
 * @author Artsiom Yudovin
 */
public clreplaced JmxAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void tearDown() {
        if (this.context != null) {
            this.context.close();
            if (this.context.getParent() != null) {
                ((ConfigurableApplicationContext) this.context.getParent()).close();
            }
        }
    }

    @Test
    public void testDefaultMBeanExport() {
        this.context = new AnnotationConfigApplicationContext();
        this.context.register(JmxAutoConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBean(MBeanExporter.clreplaced)).isNotNull();
    }

    @Test
    public void testEnabledMBeanExport() {
        MockEnvironment env = new MockEnvironment();
        env.setProperty("spring.jmx.enabled", "true");
        this.context = new AnnotationConfigApplicationContext();
        this.context.setEnvironment(env);
        this.context.register(JmxAutoConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBean(MBeanExporter.clreplaced)).isNotNull();
    }

    @Test(expected = NoSuchBeanDefinitionException.clreplaced)
    public void testDisabledMBeanExport() {
        MockEnvironment env = new MockEnvironment();
        env.setProperty("spring.jmx.enabled", "false");
        this.context = new AnnotationConfigApplicationContext();
        this.context.setEnvironment(env);
        this.context.register(TestConfiguration.clreplaced, JmxAutoConfiguration.clreplaced);
        this.context.refresh();
        this.context.getBean(MBeanExporter.clreplaced);
    }

    @Test
    public void testDefaultDomainConfiguredOnMBeanExport() {
        MockEnvironment env = new MockEnvironment();
        env.setProperty("spring.jmx.enabled", "true");
        env.setProperty("spring.jmx.default-domain", "my-test-domain");
        env.setProperty("spring.jmx.unique-names", "true");
        this.context = new AnnotationConfigApplicationContext();
        this.context.setEnvironment(env);
        this.context.register(TestConfiguration.clreplaced, JmxAutoConfiguration.clreplaced);
        this.context.refresh();
        MBeanExporter mBeanExporter = this.context.getBean(MBeanExporter.clreplaced);
        replacedertThat(mBeanExporter).isNotNull();
        MetadataNamingStrategy naming = (MetadataNamingStrategy) ReflectionTestUtils.getField(mBeanExporter, "namingStrategy");
        replacedertThat(naming).hasFieldOrPropertyWithValue("defaultDomain", "my-test-domain");
        replacedertThat(naming).hasFieldOrPropertyWithValue("ensureUniqueRuntimeObjectNames", true);
    }

    @Test
    public void testBasicParentContext() {
        this.context = new AnnotationConfigApplicationContext();
        this.context.register(JmxAutoConfiguration.clreplaced);
        this.context.refresh();
        AnnotationConfigApplicationContext parent = this.context;
        this.context = new AnnotationConfigApplicationContext();
        this.context.setParent(parent);
        this.context.register(JmxAutoConfiguration.clreplaced);
        this.context.refresh();
    }

    @Test
    public void testParentContext() {
        this.context = new AnnotationConfigApplicationContext();
        this.context.register(JmxAutoConfiguration.clreplaced, TestConfiguration.clreplaced);
        this.context.refresh();
        AnnotationConfigApplicationContext parent = this.context;
        this.context = new AnnotationConfigApplicationContext();
        this.context.setParent(parent);
        this.context.register(JmxAutoConfiguration.clreplaced, TestConfiguration.clreplaced);
        this.context.refresh();
    }

    @Test
    public void customJmxDomain() {
        this.context = new AnnotationConfigApplicationContext();
        this.context.register(CustomJmxDomainConfiguration.clreplaced, JmxAutoConfiguration.clreplaced, IntegrationAutoConfiguration.clreplaced);
        this.context.refresh();
        IntegrationMBeanExporter mbeanExporter = this.context.getBean(IntegrationMBeanExporter.clreplaced);
        DirectFieldAccessor dfa = new DirectFieldAccessor(mbeanExporter);
        replacedertThat(dfa.getPropertyValue("domain")).isEqualTo("foo.my");
    }

    @Configuration
    @EnableIntegrationMBeanExport(defaultDomain = "foo.my")
    public static clreplaced CustomJmxDomainConfiguration {
    }

    @Configuration
    public static clreplaced TestConfiguration {

        @Bean
        public Counter counter() {
            return new Counter();
        }

        @ManagedResource
        public static clreplaced Counter {

            private int counter = 0;

            @ManagedAttribute
            public int get() {
                return this.counter;
            }

            @ManagedOperation
            public void increment() {
                this.counter++;
            }
        }
    }
}

19 View Source File : TomcatDataSourceConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link TomcatDataSourceConfiguration}.
 *
 * @author Dave Syer
 * @author Stephane Nicoll
 */
public clreplaced TomcatDataSourceConfigurationTests {

    private static final String PREFIX = "spring.datasource.tomcat.";

    private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    @Before
    public void init() {
        TestPropertyValues.of(PREFIX + "initialize:false").applyTo(this.context);
    }

    @Test
    public void testDataSourceExists() {
        this.context.register(TomcatDataSourceConfiguration.clreplaced);
        TestPropertyValues.of(PREFIX + "url:jdbc:h2:mem:testdb").applyTo(this.context);
        this.context.refresh();
        replacedertThat(this.context.getBean(DataSource.clreplaced)).isNotNull();
        replacedertThat(this.context.getBean(org.apache.tomcat.jdbc.pool.DataSource.clreplaced)).isNotNull();
    }

    @Test
    public void testDataSourcePropertiesOverridden() throws Exception {
        this.context.register(TomcatDataSourceConfiguration.clreplaced);
        TestPropertyValues.of(PREFIX + "url:jdbc:h2:mem:testdb", PREFIX + "testWhileIdle:true", PREFIX + "testOnBorrow:true", PREFIX + "testOnReturn:true", PREFIX + "timeBetweenEvictionRunsMillis:10000", PREFIX + "minEvictableIdleTimeMillis:12345", PREFIX + "maxWait:1234", PREFIX + "jdbcInterceptors:SlowQueryReport", PREFIX + "validationInterval:9999").applyTo(this.context);
        this.context.refresh();
        org.apache.tomcat.jdbc.pool.DataSource ds = this.context.getBean(org.apache.tomcat.jdbc.pool.DataSource.clreplaced);
        replacedertThat(ds.getUrl()).isEqualTo("jdbc:h2:mem:testdb");
        replacedertThat(ds.isTestWhileIdle()).isTrue();
        replacedertThat(ds.isTestOnBorrow()).isTrue();
        replacedertThat(ds.isTestOnReturn()).isTrue();
        replacedertThat(ds.getTimeBetweenEvictionRunsMillis()).isEqualTo(10000);
        replacedertThat(ds.getMinEvictableIdleTimeMillis()).isEqualTo(12345);
        replacedertThat(ds.getMaxWait()).isEqualTo(1234);
        replacedertThat(ds.getValidationInterval()).isEqualTo(9999L);
        replacedertDataSourceHasInterceptors(ds);
    }

    private void replacedertDataSourceHasInterceptors(DataSourceProxy ds) throws ClreplacedNotFoundException {
        PoolProperties.InterceptorDefinition[] interceptors = ds.getJdbcInterceptorsAsArray();
        for (PoolProperties.InterceptorDefinition interceptor : interceptors) {
            if (SlowQueryReport.clreplaced == interceptor.getInterceptorClreplaced()) {
                return;
            }
        }
        fail("SlowQueryReport interceptor should have been set.");
    }

    @Test
    public void testDataSourceDefaultsPreserved() {
        this.context.register(TomcatDataSourceConfiguration.clreplaced);
        TestPropertyValues.of(PREFIX + "url:jdbc:h2:mem:testdb").applyTo(this.context);
        this.context.refresh();
        org.apache.tomcat.jdbc.pool.DataSource ds = this.context.getBean(org.apache.tomcat.jdbc.pool.DataSource.clreplaced);
        replacedertThat(ds.getTimeBetweenEvictionRunsMillis()).isEqualTo(5000);
        replacedertThat(ds.getMinEvictableIdleTimeMillis()).isEqualTo(60000);
        replacedertThat(ds.getMaxWait()).isEqualTo(30000);
        replacedertThat(ds.getValidationInterval()).isEqualTo(3000L);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getField(Clreplaced<?> target, String name) {
        Field field = ReflectionUtils.findField(target, name, null);
        ReflectionUtils.makeAccessible(field);
        return (T) ReflectionUtils.getField(field, target);
    }

    @Configuration
    @EnableConfigurationProperties
    @EnableMBeanExport
    protected static clreplaced TomcatDataSourceConfiguration {

        @Bean
        @ConfigurationProperties(prefix = "spring.datasource.tomcat")
        public DataSource dataSource() {
            return DataSourceBuilder.create().type(org.apache.tomcat.jdbc.pool.DataSource.clreplaced).build();
        }
    }
}

19 View Source File : JndiDataSourceAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link JndiDataSourceAutoConfiguration}
 *
 * @author Andy Wilkinson
 */
public clreplaced JndiDataSourceAutoConfigurationTests {

    private ClreplacedLoader threadContextClreplacedLoader;

    private String initialContextFactory;

    private AnnotationConfigApplicationContext context;

    @Before
    public void setupJndi() {
        this.initialContextFactory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY);
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestableInitialContextFactory.clreplaced.getName());
    }

    @Before
    public void setupThreadContextClreplacedLoader() {
        this.threadContextClreplacedLoader = Thread.currentThread().getContextClreplacedLoader();
        Thread.currentThread().setContextClreplacedLoader(new JndiPropertiesHidingClreplacedLoader(getClreplaced().getClreplacedLoader()));
    }

    @After
    public void close() {
        TestableInitialContextFactory.clearAll();
        if (this.initialContextFactory != null) {
            System.setProperty(Context.INITIAL_CONTEXT_FACTORY, this.initialContextFactory);
        } else {
            System.clearProperty(Context.INITIAL_CONTEXT_FACTORY);
        }
        if (this.context != null) {
            this.context.close();
        }
        Thread.currentThread().setContextClreplacedLoader(this.threadContextClreplacedLoader);
    }

    @Test
    public void dataSourceIsAvailableFromJndi() throws IllegalStateException, NamingException {
        DataSource dataSource = new BasicDataSource();
        configureJndi("foo", dataSource);
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.datasource.jndi-name:foo").applyTo(this.context);
        this.context.register(JndiDataSourceAutoConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBean(DataSource.clreplaced)).isEqualTo(dataSource);
    }

    @SuppressWarnings("unchecked")
    @Test
    public void mbeanDataSourceIsExcludedFromExport() throws IllegalStateException, NamingException {
        DataSource dataSource = new BasicDataSource();
        configureJndi("foo", dataSource);
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.datasource.jndi-name:foo").applyTo(this.context);
        this.context.register(JndiDataSourceAutoConfiguration.clreplaced, MBeanExporterConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBean(DataSource.clreplaced)).isEqualTo(dataSource);
        MBeanExporter exporter = this.context.getBean(MBeanExporter.clreplaced);
        Set<String> excludedBeans = (Set<String>) new DirectFieldAccessor(exporter).getPropertyValue("excludedBeans");
        replacedertThat(excludedBeans).containsExactly("dataSource");
    }

    @SuppressWarnings("unchecked")
    @Test
    public void mbeanDataSourceIsExcludedFromExportByAllExporters() throws IllegalStateException, NamingException {
        DataSource dataSource = new BasicDataSource();
        configureJndi("foo", dataSource);
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.datasource.jndi-name:foo").applyTo(this.context);
        this.context.register(JndiDataSourceAutoConfiguration.clreplaced, MBeanExporterConfiguration.clreplaced, AnotherMBeanExporterConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBean(DataSource.clreplaced)).isEqualTo(dataSource);
        for (MBeanExporter exporter : this.context.getBeansOfType(MBeanExporter.clreplaced).values()) {
            Set<String> excludedBeans = (Set<String>) new DirectFieldAccessor(exporter).getPropertyValue("excludedBeans");
            replacedertThat(excludedBeans).containsExactly("dataSource");
        }
    }

    @SuppressWarnings("unchecked")
    @Test
    public void standardDataSourceIsNotExcludedFromExport() throws IllegalStateException, NamingException {
        DataSource dataSource = mock(DataSource.clreplaced);
        configureJndi("foo", dataSource);
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.datasource.jndi-name:foo").applyTo(this.context);
        this.context.register(JndiDataSourceAutoConfiguration.clreplaced, MBeanExporterConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBean(DataSource.clreplaced)).isEqualTo(dataSource);
        MBeanExporter exporter = this.context.getBean(MBeanExporter.clreplaced);
        Set<String> excludedBeans = (Set<String>) new DirectFieldAccessor(exporter).getPropertyValue("excludedBeans");
        replacedertThat(excludedBeans).isEmpty();
    }

    private void configureJndi(String name, DataSource dataSource) throws IllegalStateException {
        TestableInitialContextFactory.bind(name, dataSource);
    }

    private static clreplaced MBeanExporterConfiguration {

        @Bean
        MBeanExporter mbeanExporter() {
            return new MBeanExporter();
        }
    }

    private static clreplaced AnotherMBeanExporterConfiguration {

        @Bean
        MBeanExporter anotherMbeanExporter() {
            return new MBeanExporter();
        }
    }
}

19 View Source File : EmbeddedDataSourceConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link EmbeddedDataSourceConfiguration}.
 *
 * @author Dave Syer
 * @author Stephane Nicoll
 */
public clreplaced EmbeddedDataSourceConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void closeContext() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void defaultEmbeddedDatabase() {
        this.context = load();
        replacedertThat(this.context.getBean(DataSource.clreplaced)).isNotNull();
    }

    @Test
    public void generateUniqueName() throws Exception {
        this.context = load("spring.datasource.generate-unique-name=true");
        try (AnnotationConfigApplicationContext context2 = load("spring.datasource.generate-unique-name=true")) {
            DataSource dataSource = this.context.getBean(DataSource.clreplaced);
            DataSource dataSource2 = context2.getBean(DataSource.clreplaced);
            replacedertThat(getDatabaseName(dataSource)).isNotEqualTo(getDatabaseName(dataSource2));
        }
    }

    private String getDatabaseName(DataSource dataSource) throws SQLException {
        try (Connection connection = dataSource.getConnection()) {
            ResultSet catalogs = connection.getMetaData().getCatalogs();
            if (catalogs.next()) {
                return catalogs.getString(1);
            } else {
                throw new IllegalStateException("Unable to get database name");
            }
        }
    }

    private AnnotationConfigApplicationContext load(String... environment) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        TestPropertyValues.of(environment).applyTo(ctx);
        ctx.register(EmbeddedDataSourceConfiguration.clreplaced);
        ctx.refresh();
        return ctx;
    }
}

19 View Source File : EmbeddedDataSourceConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

private AnnotationConfigApplicationContext load(String... environment) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    TestPropertyValues.of(environment).applyTo(ctx);
    ctx.register(EmbeddedDataSourceConfiguration.clreplaced);
    ctx.refresh();
    return ctx;
}

/**
 * Tests for {@link DataSourceTransactionManagerAutoConfiguration}.
 *
 * @author Dave Syer
 * @author Stephane Nicoll
 * @author Kazuki Shimizu
 */
public clreplaced DataSourceTransactionManagerAutoConfigurationTests {

    private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    @Test
    public void testDataSourceExists() {
        this.context.register(EmbeddedDataSourceConfiguration.clreplaced, DataSourceTransactionManagerAutoConfiguration.clreplaced, TransactionAutoConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBean(DataSource.clreplaced)).isNotNull();
        replacedertThat(this.context.getBean(DataSourceTransactionManager.clreplaced)).isNotNull();
    }

    @Test
    public void testNoDataSourceExists() {
        this.context.register(DataSourceTransactionManagerAutoConfiguration.clreplaced, TransactionAutoConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBeanNamesForType(DataSource.clreplaced)).isEmpty();
        replacedertThat(this.context.getBeanNamesForType(DataSourceTransactionManager.clreplaced)).isEmpty();
    }

    @Test
    public void testManualConfiguration() {
        this.context.register(EmbeddedDataSourceConfiguration.clreplaced, DataSourceTransactionManagerAutoConfiguration.clreplaced, TransactionAutoConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBean(DataSource.clreplaced)).isNotNull();
        replacedertThat(this.context.getBean(DataSourceTransactionManager.clreplaced)).isNotNull();
    }

    @Test
    public void testExistingTransactionManager() {
        this.context.register(TransactionManagerConfiguration.clreplaced, EmbeddedDataSourceConfiguration.clreplaced, DataSourceTransactionManagerAutoConfiguration.clreplaced, TransactionAutoConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBeansOfType(PlatformTransactionManager.clreplaced)).hreplacedize(1);
        replacedertThat(this.context.getBean(PlatformTransactionManager.clreplaced)).isEqualTo(this.context.getBean("myTransactionManager"));
    }

    @Test
    public void testMultiDataSource() {
        this.context.register(MultiDataSourceConfiguration.clreplaced, DataSourceTransactionManagerAutoConfiguration.clreplaced, TransactionAutoConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBeansOfType(PlatformTransactionManager.clreplaced)).isEmpty();
    }

    @Test
    public void testMultiDataSourceUsingPrimary() {
        this.context.register(MultiDataSourceUsingPrimaryConfiguration.clreplaced, DataSourceTransactionManagerAutoConfiguration.clreplaced, TransactionAutoConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBean(DataSourceTransactionManager.clreplaced)).isNotNull();
        replacedertThat(this.context.getBean(AbstractTransactionManagementConfiguration.clreplaced)).isNotNull();
    }

    @Test
    public void testCustomizeDataSourceTransactionManagerUsingProperties() {
        TestPropertyValues.of("spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true").applyTo(this.context);
        this.context.register(EmbeddedDataSourceConfiguration.clreplaced, DataSourceTransactionManagerAutoConfiguration.clreplaced, TransactionAutoConfiguration.clreplaced);
        this.context.refresh();
        DataSourceTransactionManager transactionManager = this.context.getBean(DataSourceTransactionManager.clreplaced);
        replacedertThat(transactionManager.getDefaultTimeout()).isEqualTo(30);
        replacedertThat(transactionManager.isRollbackOnCommitFailure()).isTrue();
    }

    @Configuration
    protected static clreplaced TransactionManagerConfiguration {

        @Bean
        public PlatformTransactionManager myTransactionManager() {
            return mock(PlatformTransactionManager.clreplaced);
        }
    }
}

19 View Source File : EntityScanPackagesTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link EnreplacedyScanPackages}.
 *
 * @author Phillip Webb
 */
public clreplaced EnreplacedyScanPackagesTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void cleanup() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void getWhenNoneRegisteredShouldReturnNone() {
        this.context = new AnnotationConfigApplicationContext();
        this.context.refresh();
        EnreplacedyScanPackages packages = EnreplacedyScanPackages.get(this.context);
        replacedertThat(packages).isNotNull();
        replacedertThat(packages.getPackageNames()).isEmpty();
    }

    @Test
    public void getShouldReturnRegisterPackages() {
        this.context = new AnnotationConfigApplicationContext();
        EnreplacedyScanPackages.register(this.context, "a", "b");
        EnreplacedyScanPackages.register(this.context, "b", "c");
        this.context.refresh();
        EnreplacedyScanPackages packages = EnreplacedyScanPackages.get(this.context);
        replacedertThat(packages.getPackageNames()).containsExactly("a", "b", "c");
    }

    @Test
    public void registerFromArrayWhenRegistryIsNullShouldThrowException() {
        replacedertThatIllegalArgumentException().isThrownBy(() -> EnreplacedyScanPackages.register(null)).withMessageContaining("Registry must not be null");
    }

    @Test
    public void registerFromArrayWhenPackageNamesIsNullShouldThrowException() {
        this.context = new AnnotationConfigApplicationContext();
        replacedertThatIllegalArgumentException().isThrownBy(() -> EnreplacedyScanPackages.register(this.context, (String[]) null)).withMessageContaining("PackageNames must not be null");
    }

    @Test
    public void registerFromCollectionWhenRegistryIsNullShouldThrowException() {
        replacedertThatIllegalArgumentException().isThrownBy(() -> EnreplacedyScanPackages.register(null, Collections.emptyList())).withMessageContaining("Registry must not be null");
    }

    @Test
    public void registerFromCollectionWhenPackageNamesIsNullShouldThrowException() {
        this.context = new AnnotationConfigApplicationContext();
        replacedertThatIllegalArgumentException().isThrownBy(() -> EnreplacedyScanPackages.register(this.context, (Collection<String>) null)).withMessageContaining("PackageNames must not be null");
    }

    @Test
    public void enreplacedyScanAnnotationWhenHasValueAttributeShouldSetupPackages() {
        this.context = new AnnotationConfigApplicationContext(EnreplacedyScanValueConfig.clreplaced);
        EnreplacedyScanPackages packages = EnreplacedyScanPackages.get(this.context);
        replacedertThat(packages.getPackageNames()).containsExactly("a");
    }

    @Test
    public void enreplacedyScanAnnotationWhenHasValueAttributeShouldSetupPackagesAsm() {
        this.context = new AnnotationConfigApplicationContext();
        this.context.registerBeanDefinition("enreplacedyScanValueConfig", new RootBeanDefinition(EnreplacedyScanValueConfig.clreplaced.getName()));
        this.context.refresh();
        EnreplacedyScanPackages packages = EnreplacedyScanPackages.get(this.context);
        replacedertThat(packages.getPackageNames()).containsExactly("a");
    }

    @Test
    public void enreplacedyScanAnnotationWhenHasBasePackagesAttributeShouldSetupPackages() {
        this.context = new AnnotationConfigApplicationContext(EnreplacedyScanBasePackagesConfig.clreplaced);
        EnreplacedyScanPackages packages = EnreplacedyScanPackages.get(this.context);
        replacedertThat(packages.getPackageNames()).containsExactly("b");
    }

    @Test
    public void enreplacedyScanAnnotationWhenHasValueAndBasePackagesAttributeShouldThrow() {
        replacedertThatExceptionOfType(AnnotationConfigurationException.clreplaced).isThrownBy(() -> this.context = new AnnotationConfigApplicationContext(EnreplacedyScanValueAndBasePackagesConfig.clreplaced));
    }

    @Test
    public void enreplacedyScanAnnotationWhenHasBasePackageClreplacedesAttributeShouldSetupPackages() {
        this.context = new AnnotationConfigApplicationContext(EnreplacedyScanBasePackageClreplacedesConfig.clreplaced);
        EnreplacedyScanPackages packages = EnreplacedyScanPackages.get(this.context);
        replacedertThat(packages.getPackageNames()).containsExactly(getClreplaced().getPackage().getName());
    }

    @Test
    public void enreplacedyScanAnnotationWhenNoAttributesShouldSetupPackages() {
        this.context = new AnnotationConfigApplicationContext(EnreplacedyScanNoAttributesConfig.clreplaced);
        EnreplacedyScanPackages packages = EnreplacedyScanPackages.get(this.context);
        replacedertThat(packages.getPackageNames()).containsExactly(getClreplaced().getPackage().getName());
    }

    @Test
    public void enreplacedyScanAnnotationWhenLoadingFromMultipleConfigsShouldCombinePackages() {
        this.context = new AnnotationConfigApplicationContext(EnreplacedyScanValueConfig.clreplaced, EnreplacedyScanBasePackagesConfig.clreplaced);
        EnreplacedyScanPackages packages = EnreplacedyScanPackages.get(this.context);
        replacedertThat(packages.getPackageNames()).containsExactly("a", "b");
    }

    @Configuration
    @EnreplacedyScan("a")
    static clreplaced EnreplacedyScanValueConfig {
    }

    @Configuration
    @EnreplacedyScan(basePackages = "b")
    static clreplaced EnreplacedyScanBasePackagesConfig {
    }

    @Configuration
    @EnreplacedyScan(value = "a", basePackages = "b")
    static clreplaced EnreplacedyScanValueAndBasePackagesConfig {
    }

    @Configuration
    @EnreplacedyScan(basePackageClreplacedes = EnreplacedyScanPackagesTests.clreplaced)
    static clreplaced EnreplacedyScanBasePackageClreplacedesConfig {
    }

    @Configuration
    @EnreplacedyScan
    static clreplaced EnreplacedyScanNoAttributesConfig {
    }
}

19 View Source File : NoSuchBeanDefinitionFailureAnalyzerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

private FatalBeanException createFailure(Clreplaced<?> config, String... environment) {
    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        this.replacedyzer.setBeanFactory(context.getBeanFactory());
        TestPropertyValues.of(environment).applyTo(context);
        context.register(config);
        context.refresh();
        return null;
    } catch (FatalBeanException ex) {
        return ex;
    }
}

19 View Source File : SolrRepositoriesAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link SolrRepositoriesAutoConfiguration}.
 *
 * @author Christoph Strobl
 * @author Oliver Gierke
 */
public clreplaced SolrRepositoriesAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        this.context.close();
    }

    @Test
    public void testDefaultRepositoryConfiguration() {
        initContext(TestConfiguration.clreplaced);
        replacedertThat(this.context.getBean(CityRepository.clreplaced)).isNotNull();
        replacedertThat(this.context.getBean(SolrClient.clreplaced)).isInstanceOf(HttpSolrClient.clreplaced);
    }

    @Test
    public void testNoRepositoryConfiguration() {
        initContext(EmptyConfiguration.clreplaced);
        replacedertThat(this.context.getBean(SolrClient.clreplaced)).isInstanceOf(HttpSolrClient.clreplaced);
    }

    @Test
    public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() {
        initContext(CustomizedConfiguration.clreplaced);
        replacedertThat(this.context.getBean(CitySolrRepository.clreplaced)).isNotNull();
    }

    @Test(expected = NoSuchBeanDefinitionException.clreplaced)
    public void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() {
        initContext(SortOfInvalidCustomConfiguration.clreplaced);
        this.context.getBean(CityRepository.clreplaced);
    }

    private void initContext(Clreplaced<?> configClreplaced) {
        this.context = new AnnotationConfigApplicationContext();
        this.context.register(configClreplaced, SolrAutoConfiguration.clreplaced, SolrRepositoriesAutoConfiguration.clreplaced, PropertyPlaceholderAutoConfiguration.clreplaced);
        this.context.refresh();
    }

    @Configuration
    @TestAutoConfigurationPackage(City.clreplaced)
    static clreplaced TestConfiguration {
    }

    @Configuration
    @TestAutoConfigurationPackage(EmptyDataPackage.clreplaced)
    static clreplaced EmptyConfiguration {
    }

    @Configuration
    @TestAutoConfigurationPackage(SolrRepositoriesAutoConfigurationTests.clreplaced)
    @EnableSolrRepositories(basePackageClreplacedes = CitySolrRepository.clreplaced)
    protected static clreplaced CustomizedConfiguration {
    }

    @Configuration
    @TestAutoConfigurationPackage(SolrRepositoriesAutoConfigurationTests.clreplaced)
    // To not find any repositories
    @EnableSolrRepositories("foo.bar")
    protected static clreplaced SortOfInvalidCustomConfiguration {
    }
}

19 View Source File : Neo4jRepositoriesAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link Neo4jRepositoriesAutoConfiguration}.
 *
 * @author Dave Syer
 * @author Oliver Gierke
 * @author Michael Hunger
 * @author Vince Bickers
 * @author Stephane Nicoll
 */
public clreplaced Neo4jRepositoriesAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        this.context.close();
    }

    @Test
    public void testDefaultRepositoryConfiguration() {
        prepareApplicationContext(TestConfiguration.clreplaced);
        replacedertThat(this.context.getBean(CityRepository.clreplaced)).isNotNull();
        Neo4jMappingContext mappingContext = this.context.getBean(Neo4jMappingContext.clreplaced);
        replacedertThat(mappingContext.getPersistentEnreplacedy(City.clreplaced)).isNotNull();
    }

    @Test
    public void testNoRepositoryConfiguration() {
        prepareApplicationContext(EmptyConfiguration.clreplaced);
        replacedertThat(this.context.getBean(SessionFactory.clreplaced)).isNotNull();
    }

    @Test
    public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() {
        prepareApplicationContext(CustomizedConfiguration.clreplaced);
        replacedertThat(this.context.getBean(CityNeo4jRepository.clreplaced)).isNotNull();
    }

    @Test(expected = NoSuchBeanDefinitionException.clreplaced)
    public void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() {
        prepareApplicationContext(SortOfInvalidCustomConfiguration.clreplaced);
        this.context.getBean(CityRepository.clreplaced);
    }

    private void prepareApplicationContext(Clreplaced<?>... configurationClreplacedes) {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.data.neo4j.uri=http://localhost:9797").applyTo(this.context);
        this.context.register(configurationClreplacedes);
        this.context.register(Neo4jDataAutoConfiguration.clreplaced, Neo4jRepositoriesAutoConfiguration.clreplaced, PropertyPlaceholderAutoConfiguration.clreplaced);
        this.context.refresh();
    }

    @Configuration
    @TestAutoConfigurationPackage(City.clreplaced)
    protected static clreplaced TestConfiguration {
    }

    @Configuration
    @TestAutoConfigurationPackage(EmptyDataPackage.clreplaced)
    protected static clreplaced EmptyConfiguration {
    }

    @Configuration
    @TestAutoConfigurationPackage(Neo4jRepositoriesAutoConfigurationTests.clreplaced)
    @EnableNeo4jRepositories(basePackageClreplacedes = CityNeo4jRepository.clreplaced)
    protected static clreplaced CustomizedConfiguration {
    }

    @Configuration
    // To not find any repositories
    @EnableNeo4jRepositories("foo.bar")
    @TestAutoConfigurationPackage(Neo4jRepositoriesAutoConfigurationTests.clreplaced)
    protected static clreplaced SortOfInvalidCustomConfiguration {
    }
}

19 View Source File : Neo4jPropertiesTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link Neo4jProperties}.
 *
 * @author Stephane Nicoll
 */
public clreplaced Neo4jPropertiesTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void defaultUseEmbeddedInMemoryIfAvailable() {
        Neo4jProperties properties = load(true);
        Configuration configuration = properties.createConfiguration();
        replacedertDriver(configuration, Neo4jProperties.EMBEDDED_DRIVER, null);
    }

    @Test
    public void defaultUseBoltDriverIfEmbeddedDriverIsNotAvailable() {
        Neo4jProperties properties = load(false);
        Configuration configuration = properties.createConfiguration();
        replacedertDriver(configuration, Neo4jProperties.BOLT_DRIVER, Neo4jProperties.DEFAULT_BOLT_URI);
    }

    @Test
    public void httpUriUseHttpDriver() {
        Neo4jProperties properties = load(true, "spring.data.neo4j.uri=http://localhost:7474");
        Configuration configuration = properties.createConfiguration();
        replacedertDriver(configuration, Neo4jProperties.HTTP_DRIVER, "http://localhost:7474");
    }

    @Test
    public void httpsUriUseHttpDriver() {
        Neo4jProperties properties = load(true, "spring.data.neo4j.uri=https://localhost:7474");
        Configuration configuration = properties.createConfiguration();
        replacedertDriver(configuration, Neo4jProperties.HTTP_DRIVER, "https://localhost:7474");
    }

    @Test
    public void boltUriUseBoltDriver() {
        Neo4jProperties properties = load(true, "spring.data.neo4j.uri=bolt://localhost:7687");
        Configuration configuration = properties.createConfiguration();
        replacedertDriver(configuration, Neo4jProperties.BOLT_DRIVER, "bolt://localhost:7687");
    }

    @Test
    public void fileUriUseEmbeddedServer() {
        Neo4jProperties properties = load(true, "spring.data.neo4j.uri=file://var/tmp/graph.db");
        Configuration configuration = properties.createConfiguration();
        replacedertDriver(configuration, Neo4jProperties.EMBEDDED_DRIVER, "file://var/tmp/graph.db");
    }

    @Test
    public void credentialsAreSet() {
        Neo4jProperties properties = load(true, "spring.data.neo4j.uri=http://localhost:7474", "spring.data.neo4j.username=user", "spring.data.neo4j.preplacedword=secret");
        Configuration configuration = properties.createConfiguration();
        replacedertDriver(configuration, Neo4jProperties.HTTP_DRIVER, "http://localhost:7474");
        replacedertCredentials(configuration, "user", "secret");
    }

    @Test
    public void credentialsAreSetFromUri() {
        Neo4jProperties properties = load(true, "spring.data.neo4j.uri=http://user:secret@my-server:7474");
        Configuration configuration = properties.createConfiguration();
        replacedertDriver(configuration, Neo4jProperties.HTTP_DRIVER, "http://my-server:7474");
        replacedertCredentials(configuration, "user", "secret");
    }

    @Test
    public void autoIndexNoneByDefault() {
        Neo4jProperties properties = load(true);
        Configuration configuration = properties.createConfiguration();
        replacedertThat(configuration.getAutoIndex()).isEqualTo(AutoIndexMode.NONE);
    }

    @Test
    public void autoIndexCanBeConfigured() {
        Neo4jProperties properties = load(true, "spring.data.neo4j.auto-index=validate");
        Configuration configuration = properties.createConfiguration();
        replacedertThat(configuration.getAutoIndex()).isEqualTo(AutoIndexMode.VALIDATE);
    }

    @Test
    public void embeddedModeDisabledUseBoltUri() {
        Neo4jProperties properties = load(true, "spring.data.neo4j.embedded.enabled=false");
        Configuration configuration = properties.createConfiguration();
        replacedertDriver(configuration, Neo4jProperties.BOLT_DRIVER, Neo4jProperties.DEFAULT_BOLT_URI);
    }

    @Test
    public void embeddedModeWithRelativeLocation() {
        Neo4jProperties properties = load(true, "spring.data.neo4j.uri=file:target/neo4j/my.db");
        Configuration configuration = properties.createConfiguration();
        replacedertDriver(configuration, Neo4jProperties.EMBEDDED_DRIVER, "file:target/neo4j/my.db");
    }

    private static void replacedertDriver(Configuration actual, String driver, String uri) {
        replacedertThat(actual).isNotNull();
        replacedertThat(actual.getDriverClreplacedName()).isEqualTo(driver);
        replacedertThat(actual.getURI()).isEqualTo(uri);
    }

    private static void replacedertCredentials(Configuration actual, String username, String preplacedword) {
        Credentials<?> credentials = actual.getCredentials();
        if (username == null && preplacedword == null) {
            replacedertThat(credentials).isNull();
        } else {
            replacedertThat(credentials).isNotNull();
            Object content = credentials.credentials();
            replacedertThat(content).isInstanceOf(String.clreplaced);
            String[] auth = new String(Base64.decode(((String) content).getBytes())).split(":");
            replacedertThat(auth[0]).isEqualTo(username);
            replacedertThat(auth[1]).isEqualTo(preplacedword);
            replacedertThat(auth).hreplacedize(2);
        }
    }

    public Neo4jProperties load(boolean embeddedAvailable, String... environment) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        if (!embeddedAvailable) {
            ctx.setClreplacedLoader(new FilteredClreplacedLoader(EmbeddedDriver.clreplaced));
        }
        TestPropertyValues.of(environment).applyTo(ctx);
        ctx.register(TestConfiguration.clreplaced);
        ctx.refresh();
        this.context = ctx;
        return this.context.getBean(Neo4jProperties.clreplaced);
    }

    @org.springframework.context.annotation.Configuration
    @EnableConfigurationProperties(Neo4jProperties.clreplaced)
    static clreplaced TestConfiguration {
    }
}

19 View Source File : MixedNeo4jRepositoriesAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link Neo4jRepositoriesAutoConfiguration}.
 *
 * @author Dave Syer
 * @author Oliver Gierke
 * @author Michael Hunger
 * @author Vince Bickers
 * @author Stephane Nicoll
 */
public clreplaced MixedNeo4jRepositoriesAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void testDefaultRepositoryConfiguration() {
        load(TestConfiguration.clreplaced);
        replacedertThat(this.context.getBean(CountryRepository.clreplaced)).isNotNull();
    }

    @Test
    public void testMixedRepositoryConfiguration() {
        load(MixedConfiguration.clreplaced);
        replacedertThat(this.context.getBean(CountryRepository.clreplaced)).isNotNull();
        replacedertThat(this.context.getBean(CityRepository.clreplaced)).isNotNull();
    }

    @Test
    public void testJpaRepositoryConfigurationWithNeo4jTemplate() {
        load(JpaConfiguration.clreplaced);
        replacedertThat(this.context.getBean(CityRepository.clreplaced)).isNotNull();
    }

    @Test
    @Ignore
    public void testJpaRepositoryConfigurationWithNeo4jOverlap() {
        load(OverlapConfiguration.clreplaced);
        replacedertThat(this.context.getBean(CityRepository.clreplaced)).isNotNull();
    }

    @Test
    public void testJpaRepositoryConfigurationWithNeo4jOverlapDisabled() {
        load(OverlapConfiguration.clreplaced, "spring.data.neo4j.repositories.enabled:false");
        replacedertThat(this.context.getBean(CityRepository.clreplaced)).isNotNull();
    }

    private void load(Clreplaced<?> config, String... environment) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.setClreplacedLoader(new FilteredClreplacedLoader(EmbeddedDriver.clreplaced));
        TestPropertyValues.of(environment).and("spring.datasource.initialization-mode=never").applyTo(context);
        context.register(config);
        context.register(DataSourceAutoConfiguration.clreplaced, HibernateJpaAutoConfiguration.clreplaced, JpaRepositoriesAutoConfiguration.clreplaced, Neo4jDataAutoConfiguration.clreplaced, Neo4jRepositoriesAutoConfiguration.clreplaced);
        context.refresh();
        this.context = context;
    }

    @Configuration
    @TestAutoConfigurationPackage(EmptyMarker.clreplaced)
    // Not this package or its parent
    @EnableNeo4jRepositories(basePackageClreplacedes = Country.clreplaced)
    protected static clreplaced TestConfiguration {
    }

    @Configuration
    @TestAutoConfigurationPackage(EmptyMarker.clreplaced)
    @EnableNeo4jRepositories(basePackageClreplacedes = Country.clreplaced)
    @EnreplacedyScan(basePackageClreplacedes = City.clreplaced)
    @EnableJpaRepositories(basePackageClreplacedes = CityRepository.clreplaced)
    protected static clreplaced MixedConfiguration {
    }

    @Configuration
    @TestAutoConfigurationPackage(EmptyMarker.clreplaced)
    @EnreplacedyScan(basePackageClreplacedes = City.clreplaced)
    @EnableJpaRepositories(basePackageClreplacedes = CityRepository.clreplaced)
    protected static clreplaced JpaConfiguration {
    }

    // In this one the Jpa repositories and the auto-configuration packages overlap, so
    // Neo4j will try and configure the same repositories
    @Configuration
    @TestAutoConfigurationPackage(CityRepository.clreplaced)
    @EnableJpaRepositories(basePackageClreplacedes = CityRepository.clreplaced)
    protected static clreplaced OverlapConfiguration {
    }
}

/**
 * Tests for {@link MongoRepositoriesAutoConfiguration} and
 * {@link MongoReactiveRepositoriesAutoConfiguration}.
 *
 * @author Mark Paluch
 */
public clreplaced MongoReactiveAndBlockingRepositoriesAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        this.context.close();
    }

    @Test
    public void shouldCreateInstancesForReactiveAndBlockingRepositories() {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.datasource.initialization-mode:never").applyTo(this.context);
        this.context.register(BlockingAndReactiveConfiguration.clreplaced, BaseConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBean(CityRepository.clreplaced)).isNotNull();
        replacedertThat(this.context.getBean(ReactiveCityRepository.clreplaced)).isNotNull();
    }

    @Configuration
    @TestAutoConfigurationPackage(MongoAutoConfigurationTests.clreplaced)
    @EnableMongoRepositories(basePackageClreplacedes = ReactiveCityRepository.clreplaced)
    @EnableReactiveMongoRepositories(basePackageClreplacedes = ReactiveCityRepository.clreplaced)
    protected static clreplaced BlockingAndReactiveConfiguration {
    }

    @Configuration
    @Import(Registrar.clreplaced)
    protected static clreplaced BaseConfiguration {
    }

    protected static clreplaced Registrar implements ImportSelector {

        @Override
        public String[] selectImports(AnnotationMetadata importingClreplacedMetadata) {
            List<String> names = new ArrayList<>();
            for (Clreplaced<?> type : new Clreplaced<?>[] { MongoAutoConfiguration.clreplaced, MongoReactiveAutoConfiguration.clreplaced, MongoDataAutoConfiguration.clreplaced, MongoRepositoriesAutoConfiguration.clreplaced, MongoReactiveDataAutoConfiguration.clreplaced, MongoReactiveRepositoriesAutoConfiguration.clreplaced }) {
                names.add(type.getName());
            }
            return StringUtils.toStringArray(names);
        }
    }
}

19 View Source File : MixedMongoRepositoriesAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link MongoRepositoriesAutoConfiguration}.
 *
 * @author Dave Syer
 * @author Oliver Gierke
 */
public clreplaced MixedMongoRepositoriesAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        this.context.close();
    }

    @Test
    public void testDefaultRepositoryConfiguration() {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.datasource.initialization-mode:never").applyTo(this.context);
        this.context.register(TestConfiguration.clreplaced, BaseConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBean(CountryRepository.clreplaced)).isNotNull();
    }

    @Test
    public void testMixedRepositoryConfiguration() {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.datasource.initialization-mode:never").applyTo(this.context);
        this.context.register(MixedConfiguration.clreplaced, BaseConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBean(CountryRepository.clreplaced)).isNotNull();
        replacedertThat(this.context.getBean(CityRepository.clreplaced)).isNotNull();
    }

    @Test
    public void testJpaRepositoryConfigurationWithMongoTemplate() {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.datasource.initialization-mode:never").applyTo(this.context);
        this.context.register(JpaConfiguration.clreplaced, BaseConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBean(CityRepository.clreplaced)).isNotNull();
    }

    @Test
    public void testJpaRepositoryConfigurationWithMongoOverlap() {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.datasource.initialization-mode:never").applyTo(this.context);
        this.context.register(OverlapConfiguration.clreplaced, BaseConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBean(CityRepository.clreplaced)).isNotNull();
    }

    @Test
    public void testJpaRepositoryConfigurationWithMongoOverlapDisabled() {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.datasource.initialization-mode:never", "spring.data.mongodb.repositories.type:none").applyTo(this.context);
        this.context.register(OverlapConfiguration.clreplaced, BaseConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBean(CityRepository.clreplaced)).isNotNull();
    }

    @Configuration
    @TestAutoConfigurationPackage(MongoAutoConfigurationTests.clreplaced)
    // Not this package or its parent
    @EnableMongoRepositories(basePackageClreplacedes = Country.clreplaced)
    protected static clreplaced TestConfiguration {
    }

    @Configuration
    @TestAutoConfigurationPackage(MongoAutoConfigurationTests.clreplaced)
    @EnableMongoRepositories(basePackageClreplacedes = Country.clreplaced)
    @EnreplacedyScan(basePackageClreplacedes = City.clreplaced)
    @EnableJpaRepositories(basePackageClreplacedes = CityRepository.clreplaced)
    protected static clreplaced MixedConfiguration {
    }

    @Configuration
    @TestAutoConfigurationPackage(MongoAutoConfigurationTests.clreplaced)
    @EnreplacedyScan(basePackageClreplacedes = City.clreplaced)
    @EnableJpaRepositories(basePackageClreplacedes = CityRepository.clreplaced)
    protected static clreplaced JpaConfiguration {
    }

    // In this one the Jpa repositories and the auto-configuration packages overlap, so
    // Mongo will try and configure the same repositories
    @Configuration
    @TestAutoConfigurationPackage(CityRepository.clreplaced)
    @EnableJpaRepositories(basePackageClreplacedes = CityRepository.clreplaced)
    protected static clreplaced OverlapConfiguration {
    }

    @Configuration
    @Import(Registrar.clreplaced)
    protected static clreplaced BaseConfiguration {
    }

    protected static clreplaced Registrar implements ImportSelector {

        @Override
        public String[] selectImports(AnnotationMetadata importingClreplacedMetadata) {
            List<String> names = new ArrayList<>();
            for (Clreplaced<?> type : new Clreplaced<?>[] { DataSourceAutoConfiguration.clreplaced, HibernateJpaAutoConfiguration.clreplaced, JpaRepositoriesAutoConfiguration.clreplaced, MongoAutoConfiguration.clreplaced, MongoDataAutoConfiguration.clreplaced, MongoRepositoriesAutoConfiguration.clreplaced }) {
                names.add(type.getName());
            }
            return StringUtils.toStringArray(names);
        }
    }
}

19 View Source File : LdapRepositoriesAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link LdapRepositoriesAutoConfiguration}
 *
 * @author Eddú Meléndez
 */
public clreplaced LdapRepositoriesAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void testDefaultRepositoryConfiguration() {
        load(TestConfiguration.clreplaced);
        replacedertThat(this.context.getBean(PersonRepository.clreplaced)).isNotNull();
    }

    @Test
    public void testNoRepositoryConfiguration() {
        load(EmptyConfiguration.clreplaced);
        replacedertThat(this.context.getBeanNamesForType(PersonRepository.clreplaced)).isEmpty();
    }

    @Test
    public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() {
        load(CustomizedConfiguration.clreplaced);
        replacedertThat(this.context.getBean(PersonLdapRepository.clreplaced)).isNotNull();
    }

    private void load(Clreplaced<?>... configurationClreplacedes) {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.ldap.urls:ldap://localhost:389").applyTo(this.context);
        this.context.register(configurationClreplacedes);
        this.context.register(LdapAutoConfiguration.clreplaced, LdapRepositoriesAutoConfiguration.clreplaced, PropertyPlaceholderAutoConfiguration.clreplaced);
        this.context.refresh();
    }

    @Configuration
    @TestAutoConfigurationPackage(Person.clreplaced)
    protected static clreplaced TestConfiguration {
    }

    @Configuration
    @TestAutoConfigurationPackage(EmptyDataPackage.clreplaced)
    protected static clreplaced EmptyConfiguration {
    }

    @Configuration
    @TestAutoConfigurationPackage(LdapRepositoriesAutoConfigurationTests.clreplaced)
    @EnableLdapRepositories(basePackageClreplacedes = PersonLdapRepository.clreplaced)
    protected static clreplaced CustomizedConfiguration {
    }
}

19 View Source File : ElasticsearchDataAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link ElasticsearchDataAutoConfiguration}.
 *
 * @author Phillip Webb
 * @author Artur Konczak
 */
public clreplaced ElasticsearchDataAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void templateBackOffWithNoClient() {
        this.context = new AnnotationConfigApplicationContext(ElasticsearchDataAutoConfiguration.clreplaced);
        replacedertThat(this.context.getBeansOfType(ElasticsearchTemplate.clreplaced)).isEmpty();
    }

    @Test
    public void templateExists() {
        this.context = new AnnotationConfigApplicationContext();
        new ElasticsearchNodeTemplate().doWithNode((node) -> {
            TestPropertyValues.of("spring.data.elasticsearch.properties.path.data:target/data", "spring.data.elasticsearch.properties.path.logs:target/logs", "spring.data.elasticsearch.cluster-nodes:localhost:" + node.getTcpPort()).applyTo(this.context);
            this.context.register(PropertyPlaceholderAutoConfiguration.clreplaced, ElasticsearchAutoConfiguration.clreplaced, ElasticsearchDataAutoConfiguration.clreplaced);
            this.context.refresh();
            replacedertHreplacedingleBean(ElasticsearchTemplate.clreplaced);
        });
    }

    @Test
    public void mappingContextExists() {
        this.context = new AnnotationConfigApplicationContext();
        new ElasticsearchNodeTemplate().doWithNode((node) -> {
            TestPropertyValues.of("spring.data.elasticsearch.properties.path.data:target/data", "spring.data.elasticsearch.properties.path.logs:target/logs", "spring.data.elasticsearch.cluster-nodes:localhost:" + node.getTcpPort()).applyTo(this.context);
            this.context.register(PropertyPlaceholderAutoConfiguration.clreplaced, ElasticsearchAutoConfiguration.clreplaced, ElasticsearchDataAutoConfiguration.clreplaced);
            this.context.refresh();
            replacedertHreplacedingleBean(SimpleElasticsearchMappingContext.clreplaced);
        });
    }

    @Test
    public void converterExists() {
        this.context = new AnnotationConfigApplicationContext();
        new ElasticsearchNodeTemplate().doWithNode((node) -> {
            TestPropertyValues.of("spring.data.elasticsearch.properties.path.data:target/data", "spring.data.elasticsearch.properties.path.logs:target/logs", "spring.data.elasticsearch.cluster-nodes:localhost:" + node.getTcpPort()).applyTo(this.context);
            this.context.register(PropertyPlaceholderAutoConfiguration.clreplaced, ElasticsearchAutoConfiguration.clreplaced, ElasticsearchDataAutoConfiguration.clreplaced);
            this.context.refresh();
            replacedertHreplacedingleBean(ElasticsearchConverter.clreplaced);
        });
    }

    private void replacedertHreplacedingleBean(Clreplaced<?> type) {
        replacedertThat(this.context.getBeanNamesForType(type)).hreplacedize(1);
    }
}

19 View Source File : ElasticsearchAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link ElasticsearchAutoConfiguration}.
 *
 * @author Phillip Webb
 * @author Andy Wilkinson
 */
public clreplaced ElasticsearchAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void useExistingClient() {
        this.context = new AnnotationConfigApplicationContext();
        this.context.register(CustomConfiguration.clreplaced, PropertyPlaceholderAutoConfiguration.clreplaced, ElasticsearchAutoConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBeanNamesForType(Client.clreplaced).length).isEqualTo(1);
        replacedertThat(this.context.getBean("myClient")).isSameAs(this.context.getBean(Client.clreplaced));
    }

    @Test
    public void createTransportClient() {
        this.context = new AnnotationConfigApplicationContext();
        new ElasticsearchNodeTemplate().doWithNode((node) -> {
            TestPropertyValues.of("spring.data.elasticsearch.cluster-nodes:localhost:" + node.getTcpPort(), "spring.data.elasticsearch.properties.path.home:target/es/client").applyTo(this.context);
            this.context.register(PropertyPlaceholderAutoConfiguration.clreplaced, ElasticsearchAutoConfiguration.clreplaced);
            this.context.refresh();
            List<DiscoveryNode> connectedNodes = this.context.getBean(TransportClient.clreplaced).connectedNodes();
            replacedertThat(connectedNodes).hreplacedize(1);
        });
    }

    @Configuration
    static clreplaced CustomConfiguration {

        @Bean
        public Client myClient() {
            return mock(Client.clreplaced);
        }
    }
}

19 View Source File : CouchbaseRepositoriesAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link CouchbaseRepositoriesAutoConfiguration}.
 *
 * @author Eddú Meléndez
 * @author Stephane Nicoll
 */
public clreplaced CouchbaseRepositoriesAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void couchbaseNotAvailable() {
        load(null);
        replacedertThat(this.context.getBeansOfType(CityRepository.clreplaced)).hreplacedize(0);
    }

    @Test
    public void defaultRepository() {
        load(DefaultConfiguration.clreplaced);
        replacedertThat(this.context.getBeansOfType(CityRepository.clreplaced)).hreplacedize(1);
    }

    @Test
    public void reactiveRepositories() {
        load(DefaultConfiguration.clreplaced, "spring.data.couchbase.repositories.type=reactive");
        replacedertThat(this.context.getBeansOfType(CityRepository.clreplaced)).hreplacedize(0);
    }

    @Test
    public void disabledRepositories() {
        load(DefaultConfiguration.clreplaced, "spring.data.couchbase.repositories.type=none");
        replacedertThat(this.context.getBeansOfType(CityRepository.clreplaced)).hreplacedize(0);
    }

    @Test
    public void noRepositoryAvailable() {
        load(NoRepositoryConfiguration.clreplaced);
        replacedertThat(this.context.getBeansOfType(CityRepository.clreplaced)).hreplacedize(0);
    }

    private void load(Clreplaced<?> config, String... environment) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of(environment).applyTo(context);
        if (config != null) {
            context.register(config);
        }
        context.register(PropertyPlaceholderAutoConfiguration.clreplaced, CouchbaseAutoConfiguration.clreplaced, CouchbaseDataAutoConfiguration.clreplaced, CouchbaseRepositoriesAutoConfiguration.clreplaced);
        context.refresh();
        this.context = context;
    }

    @Configuration
    @TestAutoConfigurationPackage(City.clreplaced)
    static clreplaced CouchbaseNotAvailableConfiguration {
    }

    @Configuration
    @TestAutoConfigurationPackage(City.clreplaced)
    @Import(CouchbaseTestConfigurer.clreplaced)
    static clreplaced DefaultConfiguration {
    }

    @Configuration
    @TestAutoConfigurationPackage(EmptyDataPackage.clreplaced)
    @Import(CouchbaseTestConfigurer.clreplaced)
    protected static clreplaced NoRepositoryConfiguration {
    }
}

/**
 * Tests for {@link CouchbaseReactiveRepositoriesAutoConfiguration}.
 *
 * @author Alex Derkach
 */
public clreplaced CouchbaseReactiveRepositoriesAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void couchbaseNotAvailable() {
        load(null);
        replacedertThat(this.context.getBeansOfType(ReactiveCityRepository.clreplaced)).hreplacedize(0);
    }

    @Test
    public void defaultRepository() {
        load(DefaultConfiguration.clreplaced);
        replacedertThat(this.context.getBeansOfType(ReactiveCityRepository.clreplaced)).hreplacedize(1);
    }

    @Test
    public void imperativeRepositories() {
        load(DefaultConfiguration.clreplaced, "spring.data.couchbase.repositories.type=imperative");
        replacedertThat(this.context.getBeansOfType(ReactiveCityRepository.clreplaced)).hreplacedize(0);
    }

    @Test
    public void disabledRepositories() {
        load(DefaultConfiguration.clreplaced, "spring.data.couchbase.repositories.type=none");
        replacedertThat(this.context.getBeansOfType(ReactiveCityRepository.clreplaced)).hreplacedize(0);
    }

    @Test
    public void noRepositoryAvailable() {
        load(NoRepositoryConfiguration.clreplaced);
        replacedertThat(this.context.getBeansOfType(ReactiveCityRepository.clreplaced)).hreplacedize(0);
    }

    @Test
    public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() {
        load(CustomizedConfiguration.clreplaced);
        replacedertThat(this.context.getBeansOfType(ReactiveCityCouchbaseRepository.clreplaced)).isEmpty();
    }

    private void load(Clreplaced<?> config, String... environment) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of(environment).applyTo(context);
        if (config != null) {
            context.register(config);
        }
        context.register(PropertyPlaceholderAutoConfiguration.clreplaced, CouchbaseAutoConfiguration.clreplaced, CouchbaseDataAutoConfiguration.clreplaced, CouchbaseRepositoriesAutoConfiguration.clreplaced, CouchbaseReactiveDataAutoConfiguration.clreplaced, CouchbaseReactiveRepositoriesAutoConfiguration.clreplaced);
        context.refresh();
        this.context = context;
    }

    @Configuration
    @TestAutoConfigurationPackage(City.clreplaced)
    @Import(CouchbaseTestConfigurer.clreplaced)
    static clreplaced DefaultConfiguration {
    }

    @Configuration
    @TestAutoConfigurationPackage(EmptyDataPackage.clreplaced)
    @Import(CouchbaseTestConfigurer.clreplaced)
    protected static clreplaced NoRepositoryConfiguration {
    }

    @Configuration
    @TestAutoConfigurationPackage(CouchbaseReactiveRepositoriesAutoConfigurationTests.clreplaced)
    @EnableCouchbaseRepositories(basePackageClreplacedes = CityCouchbaseRepository.clreplaced)
    @Import(CouchbaseDataAutoConfigurationTests.CustomCouchbaseConfiguration.clreplaced)
    protected static clreplaced CustomizedConfiguration {
    }
}

19 View Source File : CouchbaseReactiveDataAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link CouchbaseReactiveDataAutoConfiguration}.
 *
 * @author Alex Derkach
 */
public clreplaced CouchbaseReactiveDataAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void disabledIfCouchbaseIsNotConfigured() {
        load(null);
        replacedertThat(this.context.getBeansOfType(IndexManager.clreplaced)).isEmpty();
    }

    @Test
    public void customConfiguration() {
        load(CustomCouchbaseConfiguration.clreplaced);
        RxJavaCouchbaseTemplate rxJavaCouchbaseTemplate = this.context.getBean(RxJavaCouchbaseTemplate.clreplaced);
        replacedertThat(rxJavaCouchbaseTemplate.getDefaultConsistency()).isEqualTo(Consistency.STRONGLY_CONSISTENT);
    }

    @Test
    public void validatorIsPresent() {
        load(CouchbaseTestConfigurer.clreplaced);
        replacedertThat(this.context.getBeansOfType(ValidatingCouchbaseEventListener.clreplaced)).hreplacedize(1);
    }

    @Test
    @SuppressWarnings("unchecked")
    public void enreplacedyScanShouldSetInitialEnreplacedySet() {
        load(EnreplacedyScanConfig.clreplaced);
        CouchbaseMappingContext mappingContext = this.context.getBean(CouchbaseMappingContext.clreplaced);
        Set<Clreplaced<?>> initialEnreplacedySet = (Set<Clreplaced<?>>) ReflectionTestUtils.getField(mappingContext, "initialEnreplacedySet");
        replacedertThat(initialEnreplacedySet).containsOnly(City.clreplaced);
    }

    @Test
    public void customConversions() {
        load(CustomConversionsConfig.clreplaced);
        RxJavaCouchbaseTemplate template = this.context.getBean(RxJavaCouchbaseTemplate.clreplaced);
        replacedertThat(template.getConverter().getConversionService().canConvert(CouchbaseProperties.clreplaced, Boolean.clreplaced)).isTrue();
    }

    private void load(Clreplaced<?> config, String... environment) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of(environment).applyTo(context);
        if (config != null) {
            context.register(config);
        }
        context.register(PropertyPlaceholderAutoConfiguration.clreplaced, ValidationAutoConfiguration.clreplaced, CouchbaseAutoConfiguration.clreplaced, CouchbaseDataAutoConfiguration.clreplaced, CouchbaseReactiveDataAutoConfiguration.clreplaced);
        context.refresh();
        this.context = context;
    }

    @Configuration
    static clreplaced CustomCouchbaseConfiguration extends AbstractReactiveCouchbaseDataConfiguration {

        @Override
        protected CouchbaseConfigurer couchbaseConfigurer() {
            return new CouchbaseTestConfigurer();
        }

        @Override
        protected Consistency getDefaultConsistency() {
            return Consistency.STRONGLY_CONSISTENT;
        }
    }

    @Configuration
    @Import(CouchbaseTestConfigurer.clreplaced)
    static clreplaced CustomConversionsConfig {

        @Bean(BeanNames.COUCHBASE_CUSTOM_CONVERSIONS)
        public CouchbaseCustomConversions myCustomConversions() {
            return new CouchbaseCustomConversions(Collections.singletonList(new MyConverter()));
        }
    }

    @Configuration
    @EnreplacedyScan("org.springframework.boot.autoconfigure.data.couchbase.city")
    @Import(CustomCouchbaseConfiguration.clreplaced)
    static clreplaced EnreplacedyScanConfig {
    }

    static clreplaced MyConverter implements Converter<CouchbaseProperties, Boolean> {

        @Override
        public Boolean convert(CouchbaseProperties value) {
            return true;
        }
    }
}

19 View Source File : CouchbaseReactiveDataAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

private void load(Clreplaced<?> config, String... environment) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    TestPropertyValues.of(environment).applyTo(context);
    if (config != null) {
        context.register(config);
    }
    context.register(PropertyPlaceholderAutoConfiguration.clreplaced, ValidationAutoConfiguration.clreplaced, CouchbaseAutoConfiguration.clreplaced, CouchbaseDataAutoConfiguration.clreplaced, CouchbaseReactiveDataAutoConfiguration.clreplaced);
    context.refresh();
    this.context = context;
}

/**
 * Tests for {@link CouchbaseRepositoriesAutoConfiguration} and
 * {@link CouchbaseReactiveRepositoriesAutoConfiguration}.
 *
 * @author Stephane Nicoll
 */
public clreplaced CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        this.context.close();
    }

    @Test
    public void shouldCreateInstancesForReactiveAndImperativeRepositories() {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.datasource.initialization-mode:never").applyTo(this.context);
        this.context.register(ImperativeAndReactiveConfiguration.clreplaced, BaseConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.getBean(CityRepository.clreplaced)).isNotNull();
        replacedertThat(this.context.getBean(ReactiveCityRepository.clreplaced)).isNotNull();
    }

    @Configuration
    @TestAutoConfigurationPackage(CouchbaseAutoConfigurationTests.clreplaced)
    @EnableCouchbaseRepositories(basePackageClreplacedes = CityRepository.clreplaced)
    @EnableReactiveCouchbaseRepositories(basePackageClreplacedes = ReactiveCityRepository.clreplaced)
    protected static clreplaced ImperativeAndReactiveConfiguration {
    }

    @Configuration
    @Import({ CouchbaseTestConfigurer.clreplaced, Registrar.clreplaced })
    protected static clreplaced BaseConfiguration {
    }

    protected static clreplaced Registrar implements ImportSelector {

        @Override
        public String[] selectImports(AnnotationMetadata importingClreplacedMetadata) {
            List<String> names = new ArrayList<>();
            for (Clreplaced<?> type : new Clreplaced<?>[] { CouchbaseAutoConfiguration.clreplaced, CouchbaseDataAutoConfiguration.clreplaced, CouchbaseRepositoriesAutoConfiguration.clreplaced, CouchbaseReactiveDataAutoConfiguration.clreplaced, CouchbaseReactiveRepositoriesAutoConfiguration.clreplaced }) {
                names.add(type.getName());
            }
            return StringUtils.toStringArray(names);
        }
    }
}

19 View Source File : CouchbaseDataAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link CouchbaseDataAutoConfiguration}.
 *
 * @author Stephane Nicoll
 */
public clreplaced CouchbaseDataAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void disabledIfCouchbaseIsNotConfigured() {
        load(null);
        replacedertThat(this.context.getBeansOfType(IndexManager.clreplaced)).isEmpty();
    }

    @Test
    public void customConfiguration() {
        load(CustomCouchbaseConfiguration.clreplaced);
        CouchbaseTemplate couchbaseTemplate = this.context.getBean(CouchbaseTemplate.clreplaced);
        replacedertThat(couchbaseTemplate.getDefaultConsistency()).isEqualTo(Consistency.STRONGLY_CONSISTENT);
    }

    @Test
    public void validatorIsPresent() {
        load(CouchbaseTestConfigurer.clreplaced);
        replacedertThat(this.context.getBeansOfType(ValidatingCouchbaseEventListener.clreplaced)).hreplacedize(1);
    }

    @Test
    public void autoIndexIsDisabledByDefault() {
        load(CouchbaseTestConfigurer.clreplaced);
        IndexManager indexManager = this.context.getBean(IndexManager.clreplaced);
        replacedertThat(indexManager.isIgnoreViews()).isTrue();
        replacedertThat(indexManager.isIgnoreN1qlPrimary()).isTrue();
        replacedertThat(indexManager.isIgnoreN1qlSecondary()).isTrue();
    }

    @Test
    public void enableAutoIndex() {
        load(CouchbaseTestConfigurer.clreplaced, "spring.data.couchbase.auto-index=true");
        IndexManager indexManager = this.context.getBean(IndexManager.clreplaced);
        replacedertThat(indexManager.isIgnoreViews()).isFalse();
        replacedertThat(indexManager.isIgnoreN1qlPrimary()).isFalse();
        replacedertThat(indexManager.isIgnoreN1qlSecondary()).isFalse();
    }

    @Test
    public void changeConsistency() {
        load(CouchbaseTestConfigurer.clreplaced, "spring.data.couchbase.consistency=eventually-consistent");
        SpringBootCouchbaseDataConfiguration configuration = this.context.getBean(SpringBootCouchbaseDataConfiguration.clreplaced);
        replacedertThat(configuration.getDefaultConsistency()).isEqualTo(Consistency.EVENTUALLY_CONSISTENT);
    }

    @Test
    @SuppressWarnings("unchecked")
    public void enreplacedyScanShouldSetInitialEnreplacedySet() {
        load(EnreplacedyScanConfig.clreplaced);
        CouchbaseMappingContext mappingContext = this.context.getBean(CouchbaseMappingContext.clreplaced);
        Set<Clreplaced<?>> initialEnreplacedySet = (Set<Clreplaced<?>>) ReflectionTestUtils.getField(mappingContext, "initialEnreplacedySet");
        replacedertThat(initialEnreplacedySet).containsOnly(City.clreplaced);
    }

    @Test
    public void customConversions() {
        load(CustomConversionsConfig.clreplaced);
        CouchbaseTemplate template = this.context.getBean(CouchbaseTemplate.clreplaced);
        replacedertThat(template.getConverter().getConversionService().canConvert(CouchbaseProperties.clreplaced, Boolean.clreplaced)).isTrue();
    }

    private void load(Clreplaced<?> config, String... environment) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of(environment).applyTo(context);
        if (config != null) {
            context.register(config);
        }
        context.register(PropertyPlaceholderAutoConfiguration.clreplaced, ValidationAutoConfiguration.clreplaced, CouchbaseAutoConfiguration.clreplaced, CouchbaseDataAutoConfiguration.clreplaced);
        context.refresh();
        this.context = context;
    }

    @Configuration
    static clreplaced CustomCouchbaseConfiguration extends AbstractCouchbaseDataConfiguration {

        @Override
        protected CouchbaseConfigurer couchbaseConfigurer() {
            return new CouchbaseTestConfigurer();
        }

        @Override
        protected Consistency getDefaultConsistency() {
            return Consistency.STRONGLY_CONSISTENT;
        }
    }

    @Configuration
    @Import(CouchbaseTestConfigurer.clreplaced)
    static clreplaced CustomConversionsConfig {

        @Bean(BeanNames.COUCHBASE_CUSTOM_CONVERSIONS)
        public CouchbaseCustomConversions myCustomConversions() {
            return new CouchbaseCustomConversions(Collections.singletonList(new MyConverter()));
        }
    }

    @Configuration
    @EnreplacedyScan("org.springframework.boot.autoconfigure.data.couchbase.city")
    @Import(CustomCouchbaseConfiguration.clreplaced)
    static clreplaced EnreplacedyScanConfig {
    }

    static clreplaced MyConverter implements Converter<CouchbaseProperties, Boolean> {

        @Override
        public Boolean convert(CouchbaseProperties value) {
            return true;
        }
    }
}

19 View Source File : CouchbaseDataAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

private void load(Clreplaced<?> config, String... environment) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    TestPropertyValues.of(environment).applyTo(context);
    if (config != null) {
        context.register(config);
    }
    context.register(PropertyPlaceholderAutoConfiguration.clreplaced, ValidationAutoConfiguration.clreplaced, CouchbaseAutoConfiguration.clreplaced, CouchbaseDataAutoConfiguration.clreplaced);
    context.refresh();
    this.context = context;
}

19 View Source File : CassandraReactiveDataAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link CreplacedandraReactiveDataAutoConfiguration}.
 *
 * @author Eddú Meléndez
 * @author Stephane Nicoll
 * @author Mark Paluch
 */
public clreplaced CreplacedandraReactiveDataAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void templateExists() {
        load("spring.data.creplacedandra.keyspaceName:boot_test");
        replacedertThat(this.context.getBeanNamesForType(ReactiveCreplacedandraTemplate.clreplaced)).hreplacedize(1);
    }

    @Test
    @SuppressWarnings("unchecked")
    public void enreplacedyScanShouldSetInitialEnreplacedySet() {
        load(EnreplacedyScanConfig.clreplaced, "spring.data.creplacedandra.keyspaceName:boot_test");
        CreplacedandraMappingContext mappingContext = this.context.getBean(CreplacedandraMappingContext.clreplaced);
        Set<Clreplaced<?>> initialEnreplacedySet = (Set<Clreplaced<?>>) ReflectionTestUtils.getField(mappingContext, "initialEnreplacedySet");
        replacedertThat(initialEnreplacedySet).containsOnly(City.clreplaced);
    }

    @Test
    public void userTypeResolverShouldBeSet() {
        load("spring.data.creplacedandra.keyspaceName:boot_test");
        CreplacedandraMappingContext mappingContext = this.context.getBean(CreplacedandraMappingContext.clreplaced);
        replacedertThat(ReflectionTestUtils.getField(mappingContext, "userTypeResolver")).isInstanceOf(SimpleUserTypeResolver.clreplaced);
    }

    private void load(String... environment) {
        load(null, environment);
    }

    private void load(Clreplaced<?> config, String... environment) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        TestPropertyValues.of(environment).applyTo(ctx);
        if (config != null) {
            ctx.register(config);
        }
        ctx.register(TestConfiguration.clreplaced, CreplacedandraAutoConfiguration.clreplaced, CreplacedandraDataAutoConfiguration.clreplaced, CreplacedandraReactiveDataAutoConfiguration.clreplaced);
        ctx.refresh();
        this.context = ctx;
    }

    @Configuration
    static clreplaced TestConfiguration {

        @Bean
        public Session session() {
            return mock(Session.clreplaced);
        }
    }

    @Configuration
    @EnreplacedyScan("org.springframework.boot.autoconfigure.data.creplacedandra.city")
    static clreplaced EnreplacedyScanConfig {
    }
}

19 View Source File : CassandraDataAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link CreplacedandraDataAutoConfiguration}.
 *
 * @author Eddú Meléndez
 * @author Mark Paluch
 * @author Stephane Nicoll
 */
public clreplaced CreplacedandraDataAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void templateExists() {
        load(TestExcludeConfiguration.clreplaced);
        replacedertThat(this.context.getBeanNamesForType(CreplacedandraTemplate.clreplaced).length).isEqualTo(1);
    }

    @Test
    @SuppressWarnings("unchecked")
    public void enreplacedyScanShouldSetInitialEnreplacedySet() {
        load(EnreplacedyScanConfig.clreplaced);
        CreplacedandraMappingContext mappingContext = this.context.getBean(CreplacedandraMappingContext.clreplaced);
        Set<Clreplaced<?>> initialEnreplacedySet = (Set<Clreplaced<?>>) ReflectionTestUtils.getField(mappingContext, "initialEnreplacedySet");
        replacedertThat(initialEnreplacedySet).containsOnly(City.clreplaced);
    }

    @Test
    public void userTypeResolverShouldBeSet() {
        load();
        CreplacedandraMappingContext mappingContext = this.context.getBean(CreplacedandraMappingContext.clreplaced);
        replacedertThat(ReflectionTestUtils.getField(mappingContext, "userTypeResolver")).isInstanceOf(SimpleUserTypeResolver.clreplaced);
    }

    @Test
    public void defaultConversions() {
        load();
        CreplacedandraTemplate template = this.context.getBean(CreplacedandraTemplate.clreplaced);
        replacedertThat(template.getConverter().getConversionService().canConvert(Person.clreplaced, String.clreplaced)).isFalse();
    }

    @Test
    public void customConversions() {
        load(CustomConversionConfig.clreplaced);
        CreplacedandraTemplate template = this.context.getBean(CreplacedandraTemplate.clreplaced);
        replacedertThat(template.getConverter().getConversionService().canConvert(Person.clreplaced, String.clreplaced)).isTrue();
    }

    public void load(Clreplaced<?>... config) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.data.creplacedandra.keyspaceName:boot_test").applyTo(ctx);
        if (!ObjectUtils.isEmpty(config)) {
            ctx.register(config);
        }
        ctx.register(TestConfiguration.clreplaced, CreplacedandraAutoConfiguration.clreplaced, CreplacedandraDataAutoConfiguration.clreplaced);
        ctx.refresh();
        this.context = ctx;
    }

    @Configuration
    @ComponentScan(excludeFilters = @ComponentScan.Filter(clreplacedes = { Session.clreplaced }, type = FilterType.replacedIGNABLE_TYPE))
    static clreplaced TestExcludeConfiguration {
    }

    @Configuration
    static clreplaced TestConfiguration {

        @Bean
        public Session getObject() {
            return mock(Session.clreplaced);
        }
    }

    @Configuration
    @EnreplacedyScan("org.springframework.boot.autoconfigure.data.creplacedandra.city")
    static clreplaced EnreplacedyScanConfig {
    }

    @Configuration
    static clreplaced CustomConversionConfig {

        @Bean
        public CreplacedandraCustomConversions myCreplacedandraCustomConversions() {
            return new CreplacedandraCustomConversions(Collections.singletonList(new MyConverter()));
        }
    }

    private static clreplaced MyConverter implements Converter<Person, String> {

        @Override
        public String convert(Person o) {
            return null;
        }
    }

    private static clreplaced Person {
    }
}

/**
 * Tests for {@link PersistenceExceptionTranslationAutoConfiguration}
 *
 * @author Andy Wilkinson
 * @author Stephane Nicoll
 */
public clreplaced PersistenceExceptionTranslationAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void exceptionTranslationPostProcessorUsesCglibByDefault() {
        this.context = new AnnotationConfigApplicationContext(PersistenceExceptionTranslationAutoConfiguration.clreplaced);
        Map<String, PersistenceExceptionTranslationPostProcessor> beans = this.context.getBeansOfType(PersistenceExceptionTranslationPostProcessor.clreplaced);
        replacedertThat(beans).hreplacedize(1);
        replacedertThat(beans.values().iterator().next().isProxyTargetClreplaced()).isTrue();
    }

    @Test
    public void exceptionTranslationPostProcessorCanBeConfiguredToUseJdkProxy() {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.aop.proxy-target-clreplaced=false").applyTo(this.context);
        this.context.register(PersistenceExceptionTranslationAutoConfiguration.clreplaced);
        this.context.refresh();
        Map<String, PersistenceExceptionTranslationPostProcessor> beans = this.context.getBeansOfType(PersistenceExceptionTranslationPostProcessor.clreplaced);
        replacedertThat(beans).hreplacedize(1);
        replacedertThat(beans.values().iterator().next().isProxyTargetClreplaced()).isFalse();
    }

    @Test
    public void exceptionTranslationPostProcessorCanBeDisabled() {
        this.context = new AnnotationConfigApplicationContext();
        TestPropertyValues.of("spring.dao.exceptiontranslation.enabled=false").applyTo(this.context);
        this.context.register(PersistenceExceptionTranslationAutoConfiguration.clreplaced);
        this.context.refresh();
        Map<String, PersistenceExceptionTranslationPostProcessor> beans = this.context.getBeansOfType(PersistenceExceptionTranslationPostProcessor.clreplaced);
        replacedertThat(beans.entrySet()).isEmpty();
    }

    @Test(expected = IllegalArgumentException.clreplaced)
    public void persistOfNullThrowsIllegalArgumentExceptionWithoutExceptionTranslation() {
        this.context = new AnnotationConfigApplicationContext(EmbeddedDataSourceConfiguration.clreplaced, HibernateJpaAutoConfiguration.clreplaced, TestConfiguration.clreplaced);
        this.context.getBean(TestRepository.clreplaced).doSomething();
    }

    @Test(expected = InvalidDataAccessApiUsageException.clreplaced)
    public void persistOfNullThrowsInvalidDataAccessApiUsageExceptionWithExceptionTranslation() {
        this.context = new AnnotationConfigApplicationContext(EmbeddedDataSourceConfiguration.clreplaced, HibernateJpaAutoConfiguration.clreplaced, TestConfiguration.clreplaced, PersistenceExceptionTranslationAutoConfiguration.clreplaced);
        this.context.getBean(TestRepository.clreplaced).doSomething();
    }

    @Configuration
    static clreplaced TestConfiguration {

        @Bean
        public TestRepository testRepository(EnreplacedyManagerFactory enreplacedyManagerFactory) {
            return new TestRepository(enreplacedyManagerFactory.createEnreplacedyManager());
        }
    }

    @Repository
    private static clreplaced TestRepository {

        private final EnreplacedyManager enreplacedyManager;

        TestRepository(EnreplacedyManager enreplacedyManager) {
            this.enreplacedyManager = enreplacedyManager;
        }

        public void doSomething() {
            this.enreplacedyManager.persist(null);
        }
    }
}

19 View Source File : PropertyPlaceholderAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link PropertyPlaceholderAutoConfiguration}.
 *
 * @author Dave Syer
 */
public clreplaced PropertyPlaceholderAutoConfigurationTests {

    private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void propertyPlaceholders() {
        this.context.register(PropertyPlaceholderAutoConfiguration.clreplaced, PlaceholderConfig.clreplaced);
        TestPropertyValues.of("foo:two").applyTo(this.context);
        this.context.refresh();
        replacedertThat(this.context.getBean(PlaceholderConfig.clreplaced).getFoo()).isEqualTo("two");
    }

    @Test
    public void propertyPlaceholdersOverride() {
        this.context.register(PropertyPlaceholderAutoConfiguration.clreplaced, PlaceholderConfig.clreplaced, PlaceholdersOverride.clreplaced);
        TestPropertyValues.of("foo:two").applyTo(this.context);
        this.context.refresh();
        replacedertThat(this.context.getBean(PlaceholderConfig.clreplaced).getFoo()).isEqualTo("spam");
    }

    @Configuration
    static clreplaced PlaceholderConfig {

        @Value("${foo:bar}")
        private String foo;

        public String getFoo() {
            return this.foo;
        }
    }

    @Configuration
    static clreplaced PlaceholdersOverride {

        @Bean
        public static PropertySourcesPlaceholderConfigurer morePlaceholders() {
            PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
            configurer.setProperties(StringUtils.splitArrayElementsIntoProperties(new String[] { "foo=spam" }, "="));
            configurer.setLocalOverride(true);
            configurer.setOrder(0);
            return configurer;
        }
    }
}

19 View Source File : ConfigurationPropertiesAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link ConfigurationPropertiesAutoConfiguration}.
 *
 * @author Stephane Nicoll
 */
public clreplaced ConfigurationPropertiesAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void tearDown() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void processAnnotatedBean() {
        load(new Clreplaced[] { AutoConfig.clreplaced, SampleBean.clreplaced }, "foo.name:test");
        replacedertThat(this.context.getBean(SampleBean.clreplaced).getName()).isEqualTo("test");
    }

    @Test
    public void processAnnotatedBeanNoAutoConfig() {
        load(new Clreplaced[] { SampleBean.clreplaced }, "foo.name:test");
        replacedertThat(this.context.getBean(SampleBean.clreplaced).getName()).isEqualTo("default");
    }

    private void load(Clreplaced<?>[] configs, String... environment) {
        this.context = new AnnotationConfigApplicationContext();
        this.context.register(configs);
        TestPropertyValues.of(environment).applyTo(this.context);
        this.context.refresh();
    }

    @Configuration
    @ImportAutoConfiguration(ConfigurationPropertiesAutoConfiguration.clreplaced)
    static clreplaced AutoConfig {
    }

    @Component
    @ConfigurationProperties("foo")
    static clreplaced SampleBean {

        private String name = "default";

        public String getName() {
            return this.name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

19 View Source File : ConditionalOnSingleCandidateTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link ConditionalOnSingleCandidate}.
 *
 * @author Stephane Nicoll
 * @author Andy Wilkinson
 */
public clreplaced ConditionalOnSingleCandidateTests {

    private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void singleCandidateNoCandidate() {
        load(OnBeanSingleCandidateConfiguration.clreplaced);
        replacedertThat(this.context.containsBean("baz")).isFalse();
    }

    @Test
    public void singleCandidateOneCandidate() {
        load(FooConfiguration.clreplaced, OnBeanSingleCandidateConfiguration.clreplaced);
        replacedertThat(this.context.containsBean("baz")).isTrue();
        replacedertThat(this.context.getBean("baz")).isEqualTo("foo");
    }

    @Test
    public void singleCandidateInAncestorsOneCandidateInCurrent() {
        load();
        AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext();
        child.register(FooConfiguration.clreplaced, OnBeanSingleCandidateInAncestorsConfiguration.clreplaced);
        child.setParent(this.context);
        child.refresh();
        replacedertThat(child.containsBean("baz")).isFalse();
        child.close();
    }

    @Test
    public void singleCandidateInAncestorsOneCandidateInParent() {
        load(FooConfiguration.clreplaced);
        AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext();
        child.register(OnBeanSingleCandidateInAncestorsConfiguration.clreplaced);
        child.setParent(this.context);
        child.refresh();
        replacedertThat(child.containsBean("baz")).isTrue();
        replacedertThat(child.getBean("baz")).isEqualTo("foo");
        child.close();
    }

    @Test
    public void singleCandidateInAncestorsOneCandidateInGrandparent() {
        load(FooConfiguration.clreplaced);
        AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext();
        parent.setParent(this.context);
        parent.refresh();
        AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext();
        child.register(OnBeanSingleCandidateInAncestorsConfiguration.clreplaced);
        child.setParent(parent);
        child.refresh();
        replacedertThat(child.containsBean("baz")).isTrue();
        replacedertThat(child.getBean("baz")).isEqualTo("foo");
        child.close();
        parent.close();
    }

    @Test
    public void singleCandidateMultipleCandidates() {
        load(FooConfiguration.clreplaced, BarConfiguration.clreplaced, OnBeanSingleCandidateConfiguration.clreplaced);
        replacedertThat(this.context.containsBean("baz")).isFalse();
    }

    @Test
    public void singleCandidateMultipleCandidatesOnePrimary() {
        load(FooPrimaryConfiguration.clreplaced, BarConfiguration.clreplaced, OnBeanSingleCandidateConfiguration.clreplaced);
        replacedertThat(this.context.containsBean("baz")).isTrue();
        replacedertThat(this.context.getBean("baz")).isEqualTo("foo");
    }

    @Test
    public void singleCandidateMultipleCandidatesMultiplePrimary() {
        load(FooPrimaryConfiguration.clreplaced, BarPrimaryConfiguration.clreplaced, OnBeanSingleCandidateConfiguration.clreplaced);
        replacedertThat(this.context.containsBean("baz")).isFalse();
    }

    @Test
    public void invalidAnnotationTwoTypes() {
        replacedertThatIllegalStateException().isThrownBy(() -> load(OnBeanSingleCandidateTwoTypesConfiguration.clreplaced)).withCauseInstanceOf(IllegalArgumentException.clreplaced).withMessageContaining(OnBeanSingleCandidateTwoTypesConfiguration.clreplaced.getName());
    }

    @Test
    public void invalidAnnotationNoType() {
        replacedertThatIllegalStateException().isThrownBy(() -> load(OnBeanSingleCandidateNoTypeConfiguration.clreplaced)).withCauseInstanceOf(IllegalArgumentException.clreplaced).withMessageContaining(OnBeanSingleCandidateNoTypeConfiguration.clreplaced.getName());
    }

    @Test
    public void singleCandidateMultipleCandidatesInContextHierarchy() {
        load(FooPrimaryConfiguration.clreplaced, BarConfiguration.clreplaced);
        try (AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext()) {
            child.setParent(this.context);
            child.register(OnBeanSingleCandidateConfiguration.clreplaced);
            child.refresh();
            replacedertThat(child.containsBean("baz")).isTrue();
            replacedertThat(child.getBean("baz")).isEqualTo("foo");
        }
    }

    private void load(Clreplaced<?>... clreplacedes) {
        if (clreplacedes.length > 0) {
            this.context.register(clreplacedes);
        }
        this.context.refresh();
    }

    @Configuration
    @ConditionalOnSingleCandidate(String.clreplaced)
    protected static clreplaced OnBeanSingleCandidateConfiguration {

        @Bean
        public String baz(String s) {
            return s;
        }
    }

    @Configuration
    @ConditionalOnSingleCandidate(value = String.clreplaced, search = SearchStrategy.ANCESTORS)
    protected static clreplaced OnBeanSingleCandidateInAncestorsConfiguration {

        @Bean
        public String baz(String s) {
            return s;
        }
    }

    @Configuration
    @ConditionalOnSingleCandidate(value = String.clreplaced, type = "java.lang.String")
    protected static clreplaced OnBeanSingleCandidateTwoTypesConfiguration {
    }

    @Configuration
    @ConditionalOnSingleCandidate
    protected static clreplaced OnBeanSingleCandidateNoTypeConfiguration {
    }

    @Configuration
    protected static clreplaced FooConfiguration {

        @Bean
        public String foo() {
            return "foo";
        }
    }

    @Configuration
    protected static clreplaced FooPrimaryConfiguration {

        @Bean
        @Primary
        public String foo() {
            return "foo";
        }
    }

    @Configuration
    protected static clreplaced BarConfiguration {

        @Bean
        public String bar() {
            return "bar";
        }
    }

    @Configuration
    protected static clreplaced BarPrimaryConfiguration {

        @Bean
        @Primary
        public String bar() {
            return "bar";
        }
    }
}

19 View Source File : ConditionalOnResourceTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link ConditionalOnResource}.
 *
 * @author Dave Syer
 */
public clreplaced ConditionalOnResourceTests {

    private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    @Test
    public void testResourceExists() {
        this.context.register(BasicConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.containsBean("foo")).isTrue();
        replacedertThat(this.context.getBean("foo")).isEqualTo("foo");
    }

    @Test
    public void testResourceExistsWithPlaceholder() {
        TestPropertyValues.of("schema=schema.sql").applyTo(this.context);
        this.context.register(PlaceholderConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.containsBean("foo")).isTrue();
        replacedertThat(this.context.getBean("foo")).isEqualTo("foo");
    }

    @Test
    public void testResourceNotExists() {
        this.context.register(MissingConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.containsBean("foo")).isFalse();
    }

    @Configuration
    @ConditionalOnResource(resources = "foo")
    protected static clreplaced MissingConfiguration {

        @Bean
        public String bar() {
            return "bar";
        }
    }

    @Configuration
    @ConditionalOnResource(resources = "schema.sql")
    protected static clreplaced BasicConfiguration {

        @Bean
        public String foo() {
            return "foo";
        }
    }

    @Configuration
    @ConditionalOnResource(resources = "${schema}")
    protected static clreplaced PlaceholderConfiguration {

        @Bean
        public String foo() {
            return "foo";
        }
    }
}

19 View Source File : ConditionalOnMissingClassTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link ConditionalOnMissingClreplaced}.
 *
 * @author Dave Syer
 */
public clreplaced ConditionalOnMissingClreplacedTests {

    private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    @Test
    public void testVanillaOnClreplacedCondition() {
        this.context.register(BasicConfiguration.clreplaced, FooConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.containsBean("bar")).isFalse();
        replacedertThat(this.context.getBean("foo")).isEqualTo("foo");
    }

    @Test
    public void testMissingOnClreplacedCondition() {
        this.context.register(MissingConfiguration.clreplaced, FooConfiguration.clreplaced);
        this.context.refresh();
        replacedertThat(this.context.containsBean("bar")).isTrue();
        replacedertThat(this.context.getBean("foo")).isEqualTo("foo");
    }

    @Configuration
    @ConditionalOnMissingClreplaced("org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClreplacedTests")
    protected static clreplaced BasicConfiguration {

        @Bean
        public String bar() {
            return "bar";
        }
    }

    @Configuration
    @ConditionalOnMissingClreplaced("FOO")
    protected static clreplaced MissingConfiguration {

        @Bean
        public String bar() {
            return "bar";
        }
    }

    @Configuration
    protected static clreplaced FooConfiguration {

        @Bean
        public String foo() {
            return "foo";
        }
    }
}

19 View Source File : AutoConfigurationExcludeFilterTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link AutoConfigurationExcludeFilter}.
 *
 * @author Stephane Nicoll
 */
public clreplaced AutoConfigurationExcludeFilterTests {

    private static final Clreplaced<?> FILTERED = ExampleFilteredAutoConfiguration.clreplaced;

    private AnnotationConfigApplicationContext context;

    @After
    public void cleanUp() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void filterExcludeAutoConfiguration() {
        this.context = new AnnotationConfigApplicationContext(Config.clreplaced);
        replacedertThat(this.context.getBeansOfType(String.clreplaced)).hreplacedize(1);
        replacedertThat(this.context.getBean(String.clreplaced)).isEqualTo("test");
        replacedertThatExceptionOfType(NoSuchBeanDefinitionException.clreplaced).isThrownBy(() -> this.context.getBean(FILTERED));
    }

    @Configuration
    @ComponentScan(basePackageClreplacedes = ExampleConfiguration.clreplaced, excludeFilters = @ComponentScan.Filter(type = FilterType.CUSTOM, clreplacedes = TestAutoConfigurationExcludeFilter.clreplaced))
    static clreplaced Config {
    }

    static clreplaced TestAutoConfigurationExcludeFilter extends AutoConfigurationExcludeFilter {

        @Override
        protected List<String> getAutoConfigurations() {
            return Collections.singletonList(FILTERED.getName());
        }
    }
}

19 View Source File : InfoContributorAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link InfoContributorAutoConfiguration}.
 *
 * @author Stephane Nicoll
 */
public clreplaced InfoContributorAutoConfigurationTests {

    private AnnotationConfigApplicationContext context;

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void disableEnvContributor() {
        load("management.info.env.enabled:false");
        Map<String, InfoContributor> beans = this.context.getBeansOfType(InfoContributor.clreplaced);
        replacedertThat(beans).hreplacedize(0);
    }

    @Test
    public void defaultInfoContributorsDisabled() {
        load("management.info.defaults.enabled:false");
        Map<String, InfoContributor> beans = this.context.getBeansOfType(InfoContributor.clreplaced);
        replacedertThat(beans).hreplacedize(0);
    }

    @Test
    public void defaultInfoContributorsDisabledWithCustomOne() {
        load(CustomInfoContributorConfiguration.clreplaced, "management.info.defaults.enabled:false");
        Map<String, InfoContributor> beans = this.context.getBeansOfType(InfoContributor.clreplaced);
        replacedertThat(beans).hreplacedize(1);
        replacedertThat(this.context.getBean("customInfoContributor")).isSameAs(beans.values().iterator().next());
    }

    @SuppressWarnings("unchecked")
    @Test
    public void gitPropertiesDefaultMode() {
        load(GitPropertiesConfiguration.clreplaced);
        Map<String, InfoContributor> beans = this.context.getBeansOfType(InfoContributor.clreplaced);
        replacedertThat(beans).containsKeys("gitInfoContributor");
        Map<String, Object> content = invokeContributor(this.context.getBean("gitInfoContributor", InfoContributor.clreplaced));
        Object git = content.get("git");
        replacedertThat(git).isInstanceOf(Map.clreplaced);
        Map<String, Object> gitInfo = (Map<String, Object>) git;
        replacedertThat(gitInfo).containsOnlyKeys("branch", "commit");
    }

    @SuppressWarnings("unchecked")
    @Test
    public void gitPropertiesFullMode() {
        load(GitPropertiesConfiguration.clreplaced, "management.info.git.mode=full");
        Map<String, Object> content = invokeContributor(this.context.getBean("gitInfoContributor", InfoContributor.clreplaced));
        Object git = content.get("git");
        replacedertThat(git).isInstanceOf(Map.clreplaced);
        Map<String, Object> gitInfo = (Map<String, Object>) git;
        replacedertThat(gitInfo).containsOnlyKeys("branch", "commit", "foo");
        replacedertThat(gitInfo.get("foo")).isEqualTo("bar");
    }

    @Test
    public void customGitInfoContributor() {
        load(CustomGitInfoContributorConfiguration.clreplaced);
        replacedertThat(this.context.getBean(GitInfoContributor.clreplaced)).isSameAs(this.context.getBean("customGitInfoContributor"));
    }

    @SuppressWarnings("unchecked")
    @Test
    public void buildProperties() {
        load(BuildPropertiesConfiguration.clreplaced);
        Map<String, InfoContributor> beans = this.context.getBeansOfType(InfoContributor.clreplaced);
        replacedertThat(beans).containsKeys("buildInfoContributor");
        Map<String, Object> content = invokeContributor(this.context.getBean("buildInfoContributor", InfoContributor.clreplaced));
        Object build = content.get("build");
        replacedertThat(build).isInstanceOf(Map.clreplaced);
        Map<String, Object> buildInfo = (Map<String, Object>) build;
        replacedertThat(buildInfo).containsOnlyKeys("group", "artifact", "foo");
        replacedertThat(buildInfo.get("foo")).isEqualTo("bar");
    }

    @Test
    public void customBuildInfoContributor() {
        load(CustomBuildInfoContributorConfiguration.clreplaced);
        replacedertThat(this.context.getBean(BuildInfoContributor.clreplaced)).isSameAs(this.context.getBean("customBuildInfoContributor"));
    }

    private Map<String, Object> invokeContributor(InfoContributor contributor) {
        Info.Builder builder = new Info.Builder();
        contributor.contribute(builder);
        return builder.build().getDetails();
    }

    private void load(String... environment) {
        load(null, environment);
    }

    private void load(Clreplaced<?> config, String... environment) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        if (config != null) {
            context.register(config);
        }
        context.register(InfoContributorAutoConfiguration.clreplaced);
        TestPropertyValues.of(environment).applyTo(context);
        context.refresh();
        this.context = context;
    }

    @Configuration
    static clreplaced GitPropertiesConfiguration {

        @Bean
        public GitProperties gitProperties() {
            Properties properties = new Properties();
            properties.put("branch", "master");
            properties.put("commit.id", "abcdefg");
            properties.put("foo", "bar");
            return new GitProperties(properties);
        }
    }

    @Configuration
    static clreplaced BuildPropertiesConfiguration {

        @Bean
        public BuildProperties buildProperties() {
            Properties properties = new Properties();
            properties.put("group", "com.example");
            properties.put("artifact", "demo");
            properties.put("foo", "bar");
            return new BuildProperties(properties);
        }
    }

    @Configuration
    static clreplaced CustomInfoContributorConfiguration {

        @Bean
        public InfoContributor customInfoContributor() {
            return (builder) -> {
            };
        }
    }

    @Configuration
    static clreplaced CustomGitInfoContributorConfiguration {

        @Bean
        public GitInfoContributor customGitInfoContributor() {
            return new GitInfoContributor(new GitProperties(new Properties()));
        }
    }

    @Configuration
    static clreplaced CustomBuildInfoContributorConfiguration {

        @Bean
        public BuildInfoContributor customBuildInfoContributor() {
            return new BuildInfoContributor(new BuildProperties(new Properties()));
        }
    }
}

19 View Source File : AuditAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link AuditAutoConfiguration}.
 *
 * @author Dave Syer
 * @author Vedran Pavic
 */
public clreplaced AuditAutoConfigurationTests {

    private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    @Test
    public void defaultConfiguration() {
        registerAndRefresh(AuditAutoConfiguration.clreplaced);
        replacedertThat(this.context.getBean(AuditEventRepository.clreplaced)).isNotNull();
        replacedertThat(this.context.getBean(AuthenticationAuditListener.clreplaced)).isNotNull();
        replacedertThat(this.context.getBean(AuthorizationAuditListener.clreplaced)).isNotNull();
    }

    @Test
    public void ownAuditEventRepository() {
        registerAndRefresh(CustomAuditEventRepositoryConfiguration.clreplaced, AuditAutoConfiguration.clreplaced);
        replacedertThat(this.context.getBean(AuditEventRepository.clreplaced)).isInstanceOf(TestAuditEventRepository.clreplaced);
    }

    @Test
    public void ownAuthenticationAuditListener() {
        registerAndRefresh(CustomAuthenticationAuditListenerConfiguration.clreplaced, AuditAutoConfiguration.clreplaced);
        replacedertThat(this.context.getBean(AbstractAuthenticationAuditListener.clreplaced)).isInstanceOf(TestAuthenticationAuditListener.clreplaced);
    }

    @Test
    public void ownAuthorizationAuditListener() {
        registerAndRefresh(CustomAuthorizationAuditListenerConfiguration.clreplaced, AuditAutoConfiguration.clreplaced);
        replacedertThat(this.context.getBean(AbstractAuthorizationAuditListener.clreplaced)).isInstanceOf(TestAuthorizationAuditListener.clreplaced);
    }

    @Test
    public void ownAuditListener() {
        registerAndRefresh(CustomAuditListenerConfiguration.clreplaced, AuditAutoConfiguration.clreplaced);
        replacedertThat(this.context.getBean(AbstractAuditListener.clreplaced)).isInstanceOf(TestAuditListener.clreplaced);
    }

    private void registerAndRefresh(Clreplaced<?>... annotatedClreplacedes) {
        this.context.register(annotatedClreplacedes);
        this.context.refresh();
    }

    @Configuration
    public static clreplaced CustomAuditEventRepositoryConfiguration {

        @Bean
        public TestAuditEventRepository testAuditEventRepository() {
            return new TestAuditEventRepository();
        }
    }

    public static clreplaced TestAuditEventRepository extends InMemoryAuditEventRepository {
    }

    @Configuration
    protected static clreplaced CustomAuthenticationAuditListenerConfiguration {

        @Bean
        public TestAuthenticationAuditListener authenticationAuditListener() {
            return new TestAuthenticationAuditListener();
        }
    }

    protected static clreplaced TestAuthenticationAuditListener extends AbstractAuthenticationAuditListener {

        @Override
        public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
        }

        @Override
        public void onApplicationEvent(AbstractAuthenticationEvent event) {
        }
    }

    @Configuration
    protected static clreplaced CustomAuthorizationAuditListenerConfiguration {

        @Bean
        public TestAuthorizationAuditListener authorizationAuditListener() {
            return new TestAuthorizationAuditListener();
        }
    }

    protected static clreplaced TestAuthorizationAuditListener extends AbstractAuthorizationAuditListener {

        @Override
        public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
        }

        @Override
        public void onApplicationEvent(AbstractAuthorizationEvent event) {
        }
    }

    @Configuration
    protected static clreplaced CustomAuditListenerConfiguration {

        @Bean
        public TestAuditListener testAuditListener() {
            return new TestAuditListener();
        }
    }

    protected static clreplaced TestAuditListener extends AbstractAuditListener {

        @Override
        protected void onAuditEvent(AuditEvent event) {
        }
    }
}

See More Examples