Java Code Examples for org.springframework.mock.env.MockEnvironment

The following examples show how to use org.springframework.mock.env.MockEnvironment. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void replacementFromEnvironmentProperties() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(TestBean.class)
				.addPropertyValue("name", "${my.name}")
				.getBeanDefinition());

	MockEnvironment env = new MockEnvironment();
	env.setProperty("my.name", "myValue");

	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
	ppc.setEnvironment(env);
	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo("myValue"));
	assertThat(ppc.getAppliedPropertySources(), not(nullValue()));
}
 
Example 2
@Test
public void beanConditionOn() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.setEnvironment(new MockEnvironment().withProperty("bar.enabled", "true"));
	ctx.register(BeanConditionConfig.class);
	ctx.refresh();
	this.context = ctx;

	FooService service = this.context.getBean(FooService.class);
	Cache cache = getCache();

	Object key = new Object();
	Object value = service.getWithCondition(key);
	assertCacheHit(key, value, cache);
	value = service.getWithCondition(key);
	assertCacheHit(key, value, cache);

	assertEquals(2, this.context.getBean(BeanConditionConfig.Bar.class).count);
}
 
Example 3
Source Project: herd   Source File: ConfigurationHelperTest.java    License: Apache License 2.0 7 votes vote down vote up
@Test
public void testGetNonNegativeBigDecimalRequiredPropertyValueNegativeValueFail()
{
    ConfigurationValue configurationValue = ConfigurationValue.EMR_CLUSTER_LOWEST_CORE_INSTANCE_PRICE_PERCENTAGE;

    MockEnvironment environment = new MockEnvironment();
    environment.setProperty(configurationValue.getKey(), "-1.00");

    try
    {
        configurationHelper.getNonNegativeBigDecimalRequiredProperty(configurationValue, environment);
        fail("Should throw an IllegalStatueException when property value is not BigDecimal.");
    }
    catch (IllegalStateException e)
    {
        assertEquals(String.format("Configuration \"%s\" has an invalid non-negative BigDecimal value: \"-1.00\".", configurationValue.getKey()),
            e.getMessage());
    }
}
 
Example 4
@Test
public void explicitPropertySourcesExcludesEnvironment() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(TestBean.class)
				.addPropertyValue("name", "${my.name}")
				.getBeanDefinition());

	MutablePropertySources propertySources = new MutablePropertySources();
	propertySources.addLast(new MockPropertySource());

	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
	ppc.setPropertySources(propertySources);
	ppc.setEnvironment(new MockEnvironment().withProperty("my.name", "env"));
	ppc.setIgnoreUnresolvablePlaceholders(true);
	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo("${my.name}"));
	assertEquals(ppc.getAppliedPropertySources().iterator().next(), propertySources.iterator().next());
}
 
Example 5
@Test
public void withNonEnumerablePropertySource() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(TestBean.class)
				.addPropertyValue("name", "${foo}")
				.getBeanDefinition());

	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();

	PropertySource<?> ps = new PropertySource<Object>("simplePropertySource", new Object()) {
		@Override
		public Object getProperty(String key) {
			return "bar";
		}
	};

	MockEnvironment env = new MockEnvironment();
	env.getPropertySources().addFirst(ps);
	ppc.setEnvironment(env);

	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo("bar"));
}
 
Example 6
Source Project: herd   Source File: ConfigurationHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetBigDecimalRequiredPropertyValueBlankStringValue()
{
    ConfigurationValue configurationValue = ConfigurationValue.EMR_CLUSTER_LOWEST_CORE_INSTANCE_PRICE_PERCENTAGE;

    MockEnvironment environment = new MockEnvironment();
    environment.setProperty(configurationValue.getKey(), " ");

    try
    {
        configurationHelper.getBigDecimalRequiredProperty(configurationValue, environment);
        fail("Should throw an IllegalStatueException when property value is not BigDecimal.");
    }
    catch (IllegalStateException e)
    {
        assertEquals(String.format("Configuration \"%s\" must have a value.", configurationValue.getKey()), e.getMessage());
    }
}
 
Example 7
Source Project: herd   Source File: ConfigurationHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetPropertyReturnDefaultWhenValueConversionFails() throws Exception
{
    ConfigurationValue configurationValue = ConfigurationValue.BUSINESS_OBJECT_DATA_GET_ALL_MAX_RESULT_COUNT;
    Integer expectedValue = (Integer) configurationValue.getDefaultValue();

    MockEnvironment environment = new MockEnvironment();
    environment.setProperty(configurationValue.getKey(), "NOT_AN_INTEGER");

    executeWithoutLogging(ConfigurationHelper.class, () ->
    {
        Integer value = ConfigurationHelper.getProperty(configurationValue, Integer.class, environment);
        assertNotNull("value", value);
        assertEquals("value", expectedValue, value);
    });
}
 
Example 8
@Test
public void optionalPropertyWithoutValue() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.setConversionService(new DefaultConversionService());
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(OptionalTestBean.class)
					.addPropertyValue("name", "${my.name}")
					.getBeanDefinition());

	MockEnvironment env = new MockEnvironment();
	env.setProperty("my.name", "");

	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
	ppc.setEnvironment(env);
	ppc.setIgnoreUnresolvablePlaceholders(true);
	ppc.setNullValue("");
	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(OptionalTestBean.class).getName(), equalTo(Optional.empty()));
}
 
Example 9
@Test
public void addPropertiesFilesToEnvironmentWithSinglePropertyFromVirtualFile() {
	ConfigurableEnvironment environment = new MockEnvironment();

	MutablePropertySources propertySources = environment.getPropertySources();
	propertySources.remove(MockPropertySource.MOCK_PROPERTIES_PROPERTY_SOURCE_NAME);
	assertEquals(0, propertySources.size());

	String pair = "key = value";
	ByteArrayResource resource = new ByteArrayResource(pair.getBytes(), "from inlined property: " + pair);
	ResourceLoader resourceLoader = mock(ResourceLoader.class);
	given(resourceLoader.getResource(anyString())).willReturn(resource);

	addPropertiesFilesToEnvironment(environment, resourceLoader, FOO_LOCATIONS);
	assertEquals(1, propertySources.size());
	assertEquals("value", environment.getProperty("key"));
}
 
Example 10
@Test
public void replacementFromEnvironmentProperties() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(TestBean.class)
				.addPropertyValue("name", "${my.name}")
				.getBeanDefinition());

	MockEnvironment env = new MockEnvironment();
	env.setProperty("my.name", "myValue");

	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
	ppc.setEnvironment(env);
	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo("myValue"));
	assertThat(ppc.getAppliedPropertySources(), not(nullValue()));
}
 
Example 11
@Test
public void replacementFromEnvironmentProperties() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(TestBean.class)
				.addPropertyValue("name", "${my.name}")
				.getBeanDefinition());

	MockEnvironment env = new MockEnvironment();
	env.setProperty("my.name", "myValue");

	PropertySourcesPlaceholderConfigurer ppc =
		new PropertySourcesPlaceholderConfigurer();
	ppc.setEnvironment(env);
	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo("myValue"));
	assertThat(ppc.getAppliedPropertySources(), not(nullValue()));
}
 
Example 12
@Test
public void optionalPropertyWithValue() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.setConversionService(new DefaultConversionService());
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(OptionalTestBean.class)
					.addPropertyValue("name", "${my.name}")
					.getBeanDefinition());

	MockEnvironment env = new MockEnvironment();
	env.setProperty("my.name", "myValue");

	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
	ppc.setEnvironment(env);
	ppc.setIgnoreUnresolvablePlaceholders(true);
	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(OptionalTestBean.class).getName(), equalTo(Optional.of("myValue")));
}
 
Example 13
@Test
public void beanConditionOn() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.setEnvironment(new MockEnvironment().withProperty("bar.enabled", "true"));
	ctx.register(BeanConditionConfig.class);
	ctx.refresh();
	this.context = ctx;

	FooService service = this.context.getBean(FooService.class);
	Cache cache = getCache();

	Object key = new Object();
	Object value = service.getWithCondition(key);
	assertCacheHit(key, value, cache);
	value = service.getWithCondition(key);
	assertCacheHit(key, value, cache);

	assertEquals(2, this.context.getBean(BeanConditionConfig.Bar.class).count);
}
 
Example 14
@Test
public void explicitPropertySourcesExcludesEnvironment() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(TestBean.class)
				.addPropertyValue("name", "${my.name}")
				.getBeanDefinition());

	MutablePropertySources propertySources = new MutablePropertySources();
	propertySources.addLast(new MockPropertySource());

	PropertySourcesPlaceholderConfigurer pc = new PropertySourcesPlaceholderConfigurer();
	pc.setPropertySources(propertySources);
	pc.setEnvironment(new MockEnvironment().withProperty("my.name", "env"));
	pc.setIgnoreUnresolvablePlaceholders(true);
	pc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo("${my.name}"));
	assertEquals(pc.getAppliedPropertySources().iterator().next(), propertySources.iterator().next());
}
 
Example 15
Source Project: herd   Source File: ConfigurationHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetBooleanPropertyValueConversionFails()
{
    ConfigurationValue configurationValue = ConfigurationValue.USER_NAMESPACE_AUTHORIZATION_ENABLED;

    MockEnvironment environment = new MockEnvironment();
    environment.setProperty(configurationValue.getKey(), "NOT_A_BOOLEAN");

    try
    {
        configurationHelper.getBooleanProperty(configurationValue, environment);
        fail("Should throw an IllegalStatueException when property value is not boolean.");
    }
    catch (IllegalStateException e)
    {
        assertEquals(String.format("Configuration \"%s\" has an invalid boolean value: \"NOT_A_BOOLEAN\".", configurationValue.getKey()), e.getMessage());
    }
}
 
Example 16
@Test
public void withNonEnumerablePropertySource() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(TestBean.class)
				.addPropertyValue("name", "${foo}")
				.getBeanDefinition());

	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();

	PropertySource<?> ps = new PropertySource<Object>("simplePropertySource", new Object()) {
		@Override
		public Object getProperty(String key) {
			return "bar";
		}
	};

	MockEnvironment env = new MockEnvironment();
	env.getPropertySources().addFirst(ps);
	ppc.setEnvironment(env);

	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo("bar"));
}
 
Example 17
Source Project: herd   Source File: ConfigurationHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetRequiredPropertyIllegalStateException()
{
    ConfigurationValue configurationValue = ConfigurationValue.HERD_ENVIRONMENT;

    MockEnvironment environment = new MockEnvironment();
    environment.setProperty(configurationValue.getKey(), BLANK_TEXT);

    try
    {
        configurationHelper.getRequiredProperty(configurationValue, environment);
        fail();
    }
    catch (IllegalStateException e)
    {
        assertEquals(String.format("Configuration \"%s\" must have a value.", ConfigurationValue.HERD_ENVIRONMENT.getKey()), e.getMessage());
    }
}
 
Example 18
@Test
public void testCorrectEvents() {
	MockEnvironment environment = new MockEnvironment();
	ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class);
	EnvironmentManager environmentManager = new EnvironmentManager(environment);
	environmentManager.setApplicationEventPublisher(publisher);

	environmentManager.setProperty("foo", "bar");

	then(environment.getProperty("foo")).isEqualTo("bar");
	ArgumentCaptor<ApplicationEvent> eventCaptor = ArgumentCaptor
			.forClass(ApplicationEvent.class);
	verify(publisher, times(1)).publishEvent(eventCaptor.capture());
	then(eventCaptor.getValue()).isInstanceOf(EnvironmentChangeEvent.class);
	EnvironmentChangeEvent event = (EnvironmentChangeEvent) eventCaptor.getValue();
	then(event.getKeys()).containsExactly("foo");

	reset(publisher);

	environmentManager.reset();
	then(environment.getProperty("foo")).isNull();
	verify(publisher, times(1)).publishEvent(eventCaptor.capture());
	then(eventCaptor.getValue()).isInstanceOf(EnvironmentChangeEvent.class);
	event = (EnvironmentChangeEvent) eventCaptor.getValue();
	then(event.getKeys()).containsExactly("foo");
}
 
Example 19
@Test
public void lookupRouteFromSyncPredicates() {
	Route routeFalse = Route.async().id("routeFalse").uri("http://localhost")
			.predicate(swe -> false).build();
	Route routeFail = Route.async().id("routeFail").uri("http://localhost")
			.predicate(swe -> {
				throw new IllegalStateException("boom");
			}).build();
	Route routeTrue = Route.async().id("routeTrue").uri("http://localhost")
			.predicate(swe -> true).build();
	RouteLocator routeLocator = () -> Flux.just(routeFalse, routeFail, routeTrue)
			.hide();
	RoutePredicateHandlerMapping mapping = new RoutePredicateHandlerMapping(null,
			routeLocator, new GlobalCorsProperties(), new MockEnvironment());

	final Mono<Route> routeMono = mapping
			.lookupRoute(Mockito.mock(ServerWebExchange.class));

	StepVerifier.create(routeMono.map(Route::getId)).expectNext("routeTrue")
			.verifyComplete();

	outputCapture
			.expect(containsString("Error applying predicate for route: routeFail"));
	outputCapture.expect(containsString("java.lang.IllegalStateException: boom"));
}
 
Example 20
Source Project: data-highway   Source File: PiiReplacerConfigurationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void defaultPiiReplacer() throws Exception {
  try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
    context.setEnvironment(new MockEnvironment());
    context.register(PiiReplacerConfiguration.class);
    context.refresh();
    assertThat(context.getBean(PiiReplacer.class), is(instanceOf(DefaultPiiReplacer.class)));
  }
}
 
Example 21
Source Project: herd   Source File: ConfigurationHelperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBooleanPropertyValue()
{
    ConfigurationValue configurationValue = ConfigurationValue.USER_NAMESPACE_AUTHORIZATION_ENABLED;

    MockEnvironment environment = new MockEnvironment();
    environment.setProperty(configurationValue.getKey(), "true");

    assertEquals(Boolean.TRUE, configurationHelper.getBooleanProperty(configurationValue, environment));
}
 
Example 22
@Test
public void assertMatch() {
    MockEnvironment mockEnvironment = new MockEnvironment();
    mockEnvironment.setProperty("spring.shardingsphere.rules.master-slave.data-sources.ds_ms.master-data-source-name", "ds_master");
    ConditionContext context = Mockito.mock(ConditionContext.class);
    AnnotatedTypeMetadata metadata = Mockito.mock(AnnotatedTypeMetadata.class);
    when(context.getEnvironment()).thenReturn(mockEnvironment);
    MasterSlaveSpringBootCondition condition = new MasterSlaveSpringBootCondition();
    ConditionOutcome matchOutcome = condition.getMatchOutcome(context, metadata);
    assertThat(matchOutcome.isMatch(), is(true));
}
 
Example 23
@Test
public void trimValuesIsOffByDefault() {
	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean", rootBeanDefinition(TestBean.class)
			.addPropertyValue("name", "${my.name}")
			.getBeanDefinition());
	ppc.setEnvironment(new MockEnvironment().withProperty("my.name", " myValue  "));
	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo(" myValue  "));
}
 
Example 24
@Test
public void trimValuesIsApplied() {
	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
	ppc.setTrimValues(true);
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean", rootBeanDefinition(TestBean.class)
			.addPropertyValue("name", "${my.name}")
			.getBeanDefinition());
	ppc.setEnvironment(new MockEnvironment().withProperty("my.name", " myValue  "));
	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo("myValue"));
}
 
Example 25
@Test
public void providersWithDefaultConfigurationShouldEquals() {
    MockEnvironment environment = new MockEnvironment();

    DockerPostgresDatabaseProvider provider1 = new DockerPostgresDatabaseProvider(environment, containerCustomizers);
    DockerPostgresDatabaseProvider provider2 = new DockerPostgresDatabaseProvider(environment, containerCustomizers);

    assertThat(provider1).isEqualTo(provider2);
}
 
Example 26
Source Project: jhipster-online   Source File: WebConfigurerTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setup() {
    servletContext = spy(new MockServletContext());
    doReturn(mock(FilterRegistration.Dynamic.class))
        .when(servletContext).addFilter(anyString(), any(Filter.class));
    doReturn(mock(ServletRegistration.Dynamic.class))
        .when(servletContext).addServlet(anyString(), any(Servlet.class));

    env = new MockEnvironment();
    props = new JHipsterProperties();

    webConfigurer = new WebConfigurer(env, props);
}
 
Example 27
Source Project: herd   Source File: ConfigurationHelperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetPropertyReturnNullWhenPropertyDoesNotExistsAndNoDefaultsConfigured()
{
    ConfigurationValue configurationValue = ConfigurationValue.HIBERNATE_DIALECT;

    MockEnvironment environment = new MockEnvironment();

    String value = ConfigurationHelper.getProperty(configurationValue, String.class, environment);

    assertNull("value", value);
}
 
Example 28
Source Project: tutorials   Source File: WebConfigurerTest.java    License: MIT License 5 votes vote down vote up
@Before
public void setup() {
    servletContext = spy(new MockServletContext());
    doReturn(mock(FilterRegistration.Dynamic.class))
        .when(servletContext).addFilter(anyString(), any(Filter.class));
    doReturn(mock(ServletRegistration.Dynamic.class))
        .when(servletContext).addServlet(anyString(), any(Servlet.class));

    env = new MockEnvironment();
    props = new JHipsterProperties();

    webConfigurer = new WebConfigurer(env, props);
    metricRegistry = new MetricRegistry();
    webConfigurer.setMetricRegistry(metricRegistry);
}
 
Example 29
@Test
public void verifySpringReturnsValue() throws InvalidPropertyException {
    final MockEnvironment m = new MockEnvironment();
    m.setProperty("example.key", "value");

    final List<PropertySource> sources = new ArrayList<>(SpringConfigurationPropertySource.fromConfigurableEnvironment(m));
    final PropertyConfiguration config = new PropertyConfiguration(sources);

    final NullableProperty<String> property = new NullableStringProperty("example.key");
    Assertions.assertEquals(Optional.of("value"), config.getValue(property));
    Assertions.assertEquals(Optional.of("mockProperties"), config.getPropertySource(property));
}
 
Example 30
Source Project: alchemy   Source File: WebConfigurerTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setup() {
    servletContext = spy(new MockServletContext());
    doReturn(mock(FilterRegistration.Dynamic.class))
        .when(servletContext).addFilter(anyString(), any(Filter.class));
    doReturn(mock(ServletRegistration.Dynamic.class))
        .when(servletContext).addServlet(anyString(), any(Servlet.class));

    env = new MockEnvironment();
    props = new JHipsterProperties();

    webConfigurer = new WebConfigurer(env, props);
}