SGF-587 - Remove tthe GemfireBeanFactoryLocator and replace with SpringContextBootstrappingInitializer.

(cherry picked from commit 3fb3e6c5df6f2b376c3912840eff0f9934fd39ee)
Signed-off-by: John Blum <jblum@pivotal.io>
This commit is contained in:
John Blum
2017-01-19 18:23:19 -08:00
parent 6488fc28c0
commit c253508fca
39 changed files with 2294 additions and 1235 deletions

View File

@@ -31,6 +31,7 @@ import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.mock;
@@ -62,18 +63,16 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.access.BeanFactoryReference;
import org.springframework.core.io.Resource;
import org.springframework.data.gemfire.support.GemfireBeanFactoryLocator;
import org.springframework.data.util.ReflectionUtils;
/**
* The CacheFactoryBeanTest class is a test suite of test cases testing the contract and functionality
* of the CacheFactoryBean class.
* Unit tests for {@link CacheFactoryBean}.
*
* @author John Blum
* @see org.junit.Rule
* @see org.junit.Test
* @see org.junit.rules.ExpectedException
* @see org.mockito.Mockito
* @see org.springframework.data.gemfire.CacheFactoryBean
* @see org.apache.geode.cache.Cache
@@ -210,6 +209,7 @@ public class CacheFactoryBeanTest {
final CacheFactory mockCacheFactory = mock(CacheFactory.class);
when(mockBeanFactory.getAliases(anyString())).thenReturn(new String[0]);
when(mockCacheFactory.create()).thenReturn(mockCache);
when(mockCache.getCacheTransactionManager()).thenReturn(mockCacheTransactionManager);
when(mockCache.getDistributedSystem()).thenReturn(mockDistributedSystem);
@@ -260,6 +260,7 @@ public class CacheFactoryBeanTest {
cacheFactoryBean.setTransactionWriter(mockTransactionWriter);
cacheFactoryBean.setUseBeanFactoryLocator(true);
cacheFactoryBean.afterPropertiesSet();
cacheFactoryBean.init();
assertThat(Thread.currentThread().getContextClassLoader(), is(sameInstance(expectedThreadContextClassLoader)));
@@ -268,11 +269,11 @@ public class CacheFactoryBeanTest {
assertThat(beanFactoryLocator, is(notNullValue()));
BeanFactoryReference beanFactoryReference = beanFactoryLocator.useBeanFactory("TestGemFireCache");
BeanFactory beanFactoryReference = beanFactoryLocator.useBeanFactory("TestGemFireCache");
assertThat(beanFactoryReference, is(notNullValue()));
assertThat(beanFactoryReference.getFactory(), is(sameInstance(mockBeanFactory)));
assertThat(beanFactoryReference, is(sameInstance(mockBeanFactory)));
verify(mockBeanFactory, times(1)).getAliases(anyString());
verify(mockCacheFactory, times(1)).setPdxDiskStore(eq("TestPdxDiskStore"));
verify(mockCacheFactory, times(1)).setPdxIgnoreUnreadFields(eq(false));
verify(mockCacheFactory, times(1)).setPdxPersistent(eq(true));
@@ -707,5 +708,4 @@ public class CacheFactoryBeanTest {
assertSame(mockTransactionWriter, cacheFactoryBean.getTransactionWriter());
assertTrue(cacheFactoryBean.getUseClusterConfiguration());
}
}

View File

@@ -1,53 +0,0 @@
/*
* Copyright 2010-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.gemfire;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import org.apache.geode.cache.Cache;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Integration test for declarable support (and GEF bean factory locator).
*
* @author Costin Leau
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "cache-with-declarable-ctx.xml" })
public class DeclarableSupportTest {
@Autowired
private BeanFactory ctx;
@Test
public void testUserObject() throws Exception {
ctx.getBean(Cache.class);
assertNotNull(UserObject.THIS);
UserObject obj = UserObject.THIS;
assertSame(ctx, obj.getBeanFactory());
assertSame(ctx.getBean("bean"), obj.getProp2());
assertEquals("Enescu", obj.getProp1());
}
}

View File

@@ -1,149 +0,0 @@
/*
* Copyright 2010-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.gemfire;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.access.BeanFactoryReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Costin Leau
* @author John Blum
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "locatorContext.xml" })
@SuppressWarnings("unused")
public class GemfireBeanFactoryLocatorTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Autowired
private ApplicationContext applicationContext;
private GemfireBeanFactoryLocator locator1, locator2;
private String INSTANCE_1 = "instance1";
private String INSTANCE_2 = "instance2";
@Before
public void init() {
locator1 = new GemfireBeanFactoryLocator();
locator1.setBeanName(INSTANCE_1);
locator1.setBeanFactory(applicationContext);
locator1.afterPropertiesSet();
locator2 = new GemfireBeanFactoryLocator();
locator2.setBeanName(INSTANCE_2);
locator2.setBeanFactory(applicationContext);
locator2.afterPropertiesSet();
}
@After
public void destroy() {
BeanFactoryReference ref1;
try {
ref1 = locator1.useBeanFactory(INSTANCE_1);
ref1.release();
BeanFactoryReference ref2 = locator2.useBeanFactory(INSTANCE_2);
ref2.release();
} catch (IllegalArgumentException e) {
// it's okay
}
locator1.destroy();
locator2.destroy();
locator1 = null;
locator2 = null;
}
@Test
public void testBeanFactoryRelease() throws Exception {
}
@Test
public void testFactoryLocator() throws Exception {
BeanFactoryReference reference1 = locator1.useBeanFactory(INSTANCE_1);
BeanFactoryReference reference2 = locator2.useBeanFactory(INSTANCE_2);
BeanFactoryReference aliasRef1 = locator1.useBeanFactory("alias1");
BeanFactoryReference aliasRef2 = locator1.useBeanFactory("alias2");
// verify the static map
BeanFactory factory1 = reference1.getFactory();
BeanFactory factory2 = reference2.getFactory();
BeanFactory factory3 = reference2.getFactory();
// get the alias from different factories
BeanFactory alias1 = aliasRef1.getFactory();
BeanFactory alias2 = aliasRef2.getFactory();
assertSame(factory1, factory2);
assertSame(factory1, factory3);
// verify it's the same bean factory as the application context
assertSame(factory1, applicationContext);
// verify aliases
assertSame(alias1, alias2);
assertSame(factory1, alias1);
aliasRef1.release();
aliasRef2.release();
reference1.release();
reference2.release();
}
@Test
public void testDefaultFactoryLocator() throws Exception {
try {
locator1.useBeanFactory(null);
fail("there are more then one bean factories registered - should have thrown exception");
} catch (IllegalArgumentException e) {
// it's okay
}
}
@Test
public void factoryLocatorContract() throws Exception {
BeanFactoryReference factory1 = locator1.useBeanFactory(INSTANCE_1);
assertThat(factory1.getFactory(), is(notNullValue()));
factory1.release();
expectedException.expect(IllegalStateException.class);
expectedException.expectCause(is(nullValue(Throwable.class)));
expectedException.expectMessage("The BeanFactory has already been released or closed");
factory1.getFactory();
}
}

View File

@@ -19,29 +19,20 @@ package org.springframework.data.gemfire;
import java.lang.reflect.Field;
/**
* Utility class containing common functionality used when writing tests.
*
* @author Costin Leau
* @author John Blum
*/
public abstract class TestUtils {
@SuppressWarnings("unchecked")
public static <T> T readField(String name, Object target) throws Exception {
Class<?> targetType = target.getClass();
Field field = null;
do {
try {
field = targetType.getDeclaredField(name);
}
catch (Exception ignore) {
}
targetType = targetType.getSuperclass();
}
while (field == null && !Object.class.equals(targetType));
Field field = findField(name, target);
if (field == null) {
throw new IllegalArgumentException(String.format("Cannot find field '%1$s' in the class hierarchy of %2$s!",
name, targetType));
throw new IllegalArgumentException(String.format("Cannot find field [%1$s] in class [%2$s]",
name, target.getClass().getName()));
}
field.setAccessible(true);
@@ -49,17 +40,26 @@ public abstract class TestUtils {
return (T) field.get(target);
}
public static void cleanBeanFactoryStaticReference() {
try {
Field field = GemfireBeanFactoryLocator.class.getDeclaredField("canUseDefaultBeanFactory");
field.setAccessible(true);
field.set(null, true);
/* (non-Javadoc) */
private static Field findField(String fieldName, Object target) {
return findField(fieldName, target.getClass());
}
field = GemfireBeanFactoryLocator.class.getDeclaredField("defaultFactory");
field.setAccessible(true);
field.set(null, null);
/* (non-Javadoc) */
private static Field findField(String fieldName, Class<?> type) {
Field field = null;
} catch (Exception ex) {
while (field == null && !type.equals(Object.class)) {
try {
field = type.getDeclaredField(fieldName);
}
catch (Throwable ignore) {
}
finally {
type = type.getSuperclass();
}
}
return field;
}
}

View File

@@ -1,74 +0,0 @@
/*
* Copyright 2010-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.gemfire;
import org.apache.geode.cache.CacheLoader;
import org.apache.geode.cache.CacheLoaderException;
import org.apache.geode.cache.LoaderHelper;
/**
* User object used for testing Spring wiring.
*
* @author Costin Leau
*/
@SuppressWarnings("rawtypes")
public class UserObject extends WiringDeclarableSupport implements CacheLoader {
public static UserObject THIS;
private String prop1;
private Object prop2;
public UserObject() {
System.out.println("Initialized");
THIS = this;
}
@Override
public Object load(LoaderHelper helper) throws CacheLoaderException {
return new Object();
}
/**
* @return the prop1
*/
public String getProp1() {
return prop1;
}
/**
* @param prop1 the prop1 to set
*/
public void setProp1(String prop1) {
this.prop1 = prop1;
}
/**
* @return the prop2
*/
public Object getProp2() {
return prop2;
}
/**
* @param prop2 the prop2 to set
*/
public void setProp2(Object prop2) {
this.prop2 = prop2;
}
}

View File

@@ -24,6 +24,7 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.springframework.data.gemfire.support.GemfireBeanFactoryLocator.newBeanFactoryLocator;
import java.util.Properties;
@@ -37,7 +38,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.data.gemfire.CacheFactoryBean;
import org.springframework.data.gemfire.GemfireBeanFactoryLocator;
import org.springframework.data.gemfire.TestUtils;
import org.springframework.data.gemfire.client.ClientCacheFactoryBean;
import org.springframework.test.context.ContextConfiguration;
@@ -166,7 +166,7 @@ public class CacheNamespaceTest{
assertEquals(60.0f, evictionHeapPercentage, 0.0001);
}
@Test(expected = IllegalArgumentException.class)
@Test(expected = IllegalStateException.class)
public void testNoBeanFactoryLocator() throws Exception {
assertTrue(context.containsBean("no-bean-factory-locator-cache"));
@@ -174,15 +174,7 @@ public class CacheNamespaceTest{
assertThat(ReflectionTestUtils.getField(cacheFactoryBean, "beanFactoryLocator"), is(nullValue()));
GemfireBeanFactoryLocator beanFactoryLocator = new GemfireBeanFactoryLocator();
try {
assertNotNull(beanFactoryLocator.useBeanFactory("cache-with-name"));
beanFactoryLocator.useBeanFactory("no-bean-factory-locator-cache");
}
finally {
beanFactoryLocator.destroy();
}
newBeanFactoryLocator().useBeanFactory("no-bean-factory-locator-cache");
}
@Test

View File

@@ -0,0 +1,182 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.data.gemfire.support;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.beans.factory.BeanFactory;
/**
* Unit tests for {@link DeclarableSupport}.
*
* @author John Blum
* @see org.junit.Rule
* @see org.junit.Test
* @see org.mockito.Mock
* @see org.mockito.Mockito
* @see org.mockito.Spy
* @see org.mockito.runners.MockitoJUnitRunner
* @since 2.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class DeclarableSupportUnitTests {
@Rule
public ExpectedException exception = ExpectedException.none();
@Mock
private BeanFactory mockBeanFactoryOne;
@Mock
private BeanFactory mockBeanFactoryTwo;
@Spy
private DeclarableSupport testDeclarableSupport;
@After
public void tearDown() {
testDeclarableSupport.setBeanFactoryKey(null);
GemfireBeanFactoryLocator.BEAN_FACTORIES.clear();
}
@Test
public void setAndGetBeanFactoryKey() {
assertThat(testDeclarableSupport.getBeanFactoryKey()).isNull();
testDeclarableSupport.setBeanFactoryKey("testKey");
assertThat(testDeclarableSupport.getBeanFactoryKey()).isEqualTo("testKey");
testDeclarableSupport.setBeanFactoryKey(null);
assertThat(testDeclarableSupport.getBeanFactoryKey()).isNull();
}
@Test
public void locateBeanFactoryReturnsBeanFactory() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyOne", mockBeanFactoryOne);
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyTwo", mockBeanFactoryTwo);
testDeclarableSupport.setBeanFactoryKey("keyOne");
assertThat(testDeclarableSupport.getBeanFactoryKey()).isEqualTo("keyOne");
assertThat(testDeclarableSupport.locateBeanFactory()).isSameAs(mockBeanFactoryOne);
}
@Test
public void locateBeanFactoryWithKeyReturnsBeanFactory() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyOne", mockBeanFactoryOne);
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyTwo", mockBeanFactoryTwo);
assertThat(testDeclarableSupport.getBeanFactoryKey()).isNull();
assertThat(testDeclarableSupport.locateBeanFactory("keyTwo")).isSameAs(mockBeanFactoryTwo);
}
@Test
public void locateBeanFactoryWithoutKeyReturnsBeanFactory() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyOne", mockBeanFactoryOne);
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("refTwo", mockBeanFactoryOne);
assertThat(testDeclarableSupport.getBeanFactoryKey()).isNull();
assertThat(testDeclarableSupport.locateBeanFactory()).isSameAs(mockBeanFactoryOne);
}
@Test
public void locateBeanFactoryWithUnknownKeyHavingMultipleBeanFactoriesRegisteredThrowsIllegalArgumentException() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyOne", mockBeanFactoryOne);
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyTwo", mockBeanFactoryTwo);
testDeclarableSupport.setBeanFactoryKey("keyOne");
assertThat(testDeclarableSupport.getBeanFactoryKey()).isEqualTo("keyOne");
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("BeanFactory for key [UnknownKey] was not found");
testDeclarableSupport.locateBeanFactory("UnknownKey");
}
@Test
public void locateBeanFactoryWithoutKeyHavingMultipleBeanFactoriesRegisteredThrowsIllegalStateException() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyOne", mockBeanFactoryOne);
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyTwo", mockBeanFactoryTwo);
assertThat(testDeclarableSupport.getBeanFactoryKey()).isNull();
exception.expect(IllegalStateException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("BeanFactory key must be specified when more than one BeanFactory [keyOne, keyTwo]"
+ " is registered");
testDeclarableSupport.locateBeanFactory();
}
@Test
public void locateBeanFactoryWithKeyWhenNoBeanFactoriesAreRegisteredThrowsIllegalStateException() {
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES).isEmpty();
exception.expect(IllegalStateException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("A BeanFactory was not initialized;"
+ " Please verify the useBeanFactoryLocator property was properly set");
testDeclarableSupport.locateBeanFactory("testKey");
}
@Test
public void locateBeanFactoryWithoutKeyWhenNoBeanFactoriesAreRegisteredThrowsIllegalStateException() {
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES).isEmpty();
exception.expect(IllegalStateException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("A BeanFactory was not initialized;"
+ " Please verify the useBeanFactoryLocator property was properly set");
testDeclarableSupport.locateBeanFactory();
}
@Test
public void getBeanFactoryReturnsBeanFactory() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyOne", mockBeanFactoryOne);
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyTwo", mockBeanFactoryTwo);
testDeclarableSupport.setBeanFactoryKey("keyOne");
assertThat(testDeclarableSupport.getBeanFactoryKey()).isEqualTo("keyOne");
assertThat(testDeclarableSupport.getBeanFactory()).isSameAs(mockBeanFactoryOne);
}
@Test
public void closeIsSuccessful() {
testDeclarableSupport.close();
verify(testDeclarableSupport, times(1)).close();
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.data.gemfire.support;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.data.gemfire.util.CollectionUtils.asSet;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.gemfire.config.annotation.PeerCacheApplication;
import org.springframework.data.gemfire.test.GemfireTestBeanPostProcessor;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Integration tests using Java-based configuration for {@link GemfireBeanFactoryLocator}.
*
* @author John Blum
* @see org.junit.Test
* @see org.springframework.beans.factory.BeanFactory
* @see org.springframework.data.gemfire.config.annotation.PeerCacheApplication
* @see org.springframework.data.gemfire.support.GemfireBeanFactoryLocator
* @see org.springframework.data.gemfire.test.GemfireTestBeanPostProcessor
* @see org.springframework.test.context.ContextConfiguration
* @see org.springframework.test.context.junit4.SpringRunner
* @since 2.0.0
*/
@RunWith(SpringRunner.class)
@ContextConfiguration
public class GemfireBeanFactoryLocatorAnnotationConfigIntegrationTests {
@Autowired
@SuppressWarnings("unused")
private BeanFactory beanFactory;
@Test
public void beanFactoryContainsTestBeanFactoryLocatorBean() {
assertThat(beanFactory.containsBean("testBeanFactoryLocator")).isTrue();
GemfireBeanFactoryLocator testBeanFactoryLocator = beanFactory.getBean("testBeanFactoryLocator",
GemfireBeanFactoryLocator.class);
assertThat(testBeanFactoryLocator).isNotNull();
assertThat(testBeanFactoryLocator.getBeanFactory()).isSameAs(beanFactory);
assertThat(testBeanFactoryLocator.getAssociatedBeanName()).isEqualTo("testBeanFactoryLocator");
assertThat(testBeanFactoryLocator.getAssociatedBeanNameWithAliases()).isNotNull();
assertThat(testBeanFactoryLocator.getAssociatedBeanNameWithAliases())
.containsAll(asSet("testBeanFactoryLocator", "aliasOne", "aliasTwo"));
assertThat(beanFactory.getAliases("testBeanFactoryLocator")).containsAll(asSet("aliasOne", "aliasTwo"));
}
@Test
public void registeredBeanFactoriesIsCorrect() {
Set<String> beanNames = asSet("gemfireCache", "testBeanFactoryLocator", "aliasOne", "aliasTwo");
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES).hasSameSizeAs(beanNames);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.keySet()).containsAll(beanNames);
for (String beanName : beanNames) {
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.get(beanName)).isSameAs(beanFactory);
}
}
@SuppressWarnings("unused")
@PeerCacheApplication(useBeanFactoryLocator = true)
static class TestConfiguration {
@Bean
GemfireTestBeanPostProcessor gemfireTestBeanPostProcessor() {
return new GemfireTestBeanPostProcessor();
}
@Bean(name = { "testBeanFactoryLocator", "aliasOne", "aliasTwo" })
GemfireBeanFactoryLocator testBeanFactoryLocator() {
return new GemfireBeanFactoryLocator();
}
}
}

View File

@@ -0,0 +1,96 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.data.gemfire.support;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.data.gemfire.util.CollectionUtils.asSet;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Integration tests using XML for {@link GemfireBeanFactoryLocator}.
*
* @author John Blum
* @see org.junit.Test
* @see org.springframework.beans.factory.BeanFactory
* @see org.springframework.data.gemfire.support.GemfireBeanFactoryLocator
* @see org.springframework.test.context.ContextConfiguration
* @see org.springframework.test.context.junit4.SpringRunner
* @since 2.0.0
*/
@RunWith(SpringRunner.class)
@ContextConfiguration
public class GemfireBeanFactoryLocatorIntegrationTests {
@Autowired
@SuppressWarnings("unused")
private BeanFactory beanFactory;
@Test
public void beanFactoryContainsGemfireBeanFactoryLocatorBean() {
assertThat(beanFactory.containsBean(GemfireBeanFactoryLocator.class.getName())).isTrue();
GemfireBeanFactoryLocator gemfireBeanFactoryLocator =
beanFactory.getBean(GemfireBeanFactoryLocator.class.getName(), GemfireBeanFactoryLocator.class);
assertThat(gemfireBeanFactoryLocator).isNotNull();
assertThat(gemfireBeanFactoryLocator.getBeanFactory()).isSameAs(beanFactory);
assertThat(gemfireBeanFactoryLocator.getAssociatedBeanName())
.startsWith(GemfireBeanFactoryLocator.class.getName());
assertThat(gemfireBeanFactoryLocator.getAssociatedBeanNameWithAliases()).isNotNull();
assertThat(gemfireBeanFactoryLocator.getAssociatedBeanNameWithAliases())
.containsAll(asSet(GemfireBeanFactoryLocator.class.getName()));
assertThat(beanFactory.getAliases(GemfireBeanFactoryLocator.class.getName()))
.containsAll(asSet(GemfireBeanFactoryLocator.class.getName().concat("#0")));
}
@Test
public void beanFactoryContainsTestBeanFactoryLocatorBean() {
assertThat(beanFactory.containsBean("testBeanFactoryLocator")).isTrue();
GemfireBeanFactoryLocator testBeanFactoryLocator = beanFactory.getBean("testBeanFactoryLocator",
GemfireBeanFactoryLocator.class);
assertThat(testBeanFactoryLocator).isNotNull();
assertThat(testBeanFactoryLocator.getBeanFactory()).isSameAs(beanFactory);
assertThat(testBeanFactoryLocator.getAssociatedBeanName()).isEqualTo("testBeanFactoryLocator");
assertThat(testBeanFactoryLocator.getAssociatedBeanNameWithAliases()).isNotNull();
assertThat(testBeanFactoryLocator.getAssociatedBeanNameWithAliases())
.containsAll(asSet("testBeanFactoryLocator", "aliasOne", "aliasTwo"));
assertThat(beanFactory.getAliases("testBeanFactoryLocator")).containsAll(asSet("aliasOne", "aliasTwo"));
}
@Test
public void registeredBeanFactoriesIsCorrect() {
Set<String> beanNames = asSet("gemfire-cache", "gemfireCache", "testBeanFactoryLocator", "aliasOne", "aliasTwo",
GemfireBeanFactoryLocator.class.getName());
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.keySet()).containsAll(beanNames);
for (String beanName : beanNames) {
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.get(beanName)).isSameAs(beanFactory);
}
}
}

View File

@@ -0,0 +1,109 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.data.gemfire.support;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.data.gemfire.util.CollectionUtils.asSet;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.gemfire.CacheFactoryBean;
import org.springframework.data.gemfire.test.GemfireTestBeanPostProcessor;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Integration tests using Java-based configuration for {@link GemfireBeanFactoryLocator}.
*
* @author John Blum
* @see org.junit.Test
* @see org.springframework.beans.factory.BeanFactory
* @see org.springframework.data.gemfire.CacheFactoryBean
* @see org.springframework.data.gemfire.support.GemfireBeanFactoryLocator
* @see org.springframework.data.gemfire.test.GemfireTestBeanPostProcessor
* @see org.springframework.test.context.ContextConfiguration
* @see org.springframework.test.context.junit4.SpringRunner
* @since 2.0.0
*/
@RunWith(SpringRunner.class)
@ContextConfiguration
public class GemfireBeanFactoryLocatorJavaConfigIntegrationTests {
@Autowired
@SuppressWarnings("unused")
private BeanFactory beanFactory;
@Test
public void beanFactoryContainsTestBeanFactoryLocatorBean() {
assertThat(beanFactory.containsBean("testBeanFactoryLocator")).isTrue();
GemfireBeanFactoryLocator testBeanFactoryLocator = beanFactory.getBean("testBeanFactoryLocator",
GemfireBeanFactoryLocator.class);
assertThat(testBeanFactoryLocator).isNotNull();
assertThat(testBeanFactoryLocator.getBeanFactory()).isSameAs(beanFactory);
assertThat(testBeanFactoryLocator.getAssociatedBeanName()).isEqualTo("testBeanFactoryLocator");
assertThat(testBeanFactoryLocator.getAssociatedBeanNameWithAliases()).isNotNull();
assertThat(testBeanFactoryLocator.getAssociatedBeanNameWithAliases())
.containsAll(asSet("testBeanFactoryLocator", "aliasOne", "aliasTwo"));
assertThat(beanFactory.getAliases("testBeanFactoryLocator")).containsAll(asSet("aliasOne", "aliasTwo"));
}
@Test
public void registeredBeanFactoriesIsCorrect() {
Set<String> beanNames = asSet("gemfireCache", "testBeanFactoryLocator", "aliasOne", "aliasTwo");
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES).hasSameSizeAs(beanNames);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.keySet()).containsAll(beanNames);
for (String beanName : beanNames) {
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.get(beanName)).isSameAs(beanFactory);
}
}
@Configuration
@SuppressWarnings("unused")
static class TestConfiguration {
@Bean
GemfireTestBeanPostProcessor gemfireTestBeanPostProcessor() {
return new GemfireTestBeanPostProcessor();
}
@Bean
CacheFactoryBean gemfireCache() {
CacheFactoryBean gemfireCache = new CacheFactoryBean();
gemfireCache.setClose(true);
gemfireCache.setUseBeanFactoryLocator(true);
return gemfireCache;
}
@Bean(name = { "testBeanFactoryLocator", "aliasOne", "aliasTwo" })
GemfireBeanFactoryLocator testBeanFactoryLocator() {
return new GemfireBeanFactoryLocator();
}
}
}

View File

@@ -0,0 +1,497 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.data.gemfire.support;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.data.gemfire.support.GemfireBeanFactoryLocator.BeanFactoryReference.UNINITIALIZED_BEAN_FACTORY_REFERENCE_MESSAGE;
import static org.springframework.data.gemfire.support.GemfireBeanFactoryLocator.newBeanFactoryLocator;
import static org.springframework.data.gemfire.util.CollectionUtils.asSet;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.beans.factory.BeanFactory;
/**
* Unit tests for {@link GemfireBeanFactoryLocator}.
*
* @author John Blum
* @see org.junit.Rule
* @see org.junit.Test
* @see org.mockito.Mock
* @see org.mockito.Mockito
* @see org.mockito.runners.MockitoJUnitRunner
* @see org.springframework.data.gemfire.support.GemfireBeanFactoryLocator
* @since 2.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class GemfireBeanFactoryLocatorUnitTests {
@Rule
public ExpectedException exception = ExpectedException.none();
@Mock
private BeanFactory mockBeanFactory;
@Before
public void setup() {
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.isEmpty()).isTrue();
}
@After
public void tearDown() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.clear();
}
@Test
public void newUninitializedBeanFactorLocator() {
GemfireBeanFactoryLocator beanFactoryLocator = newBeanFactoryLocator();
assertThat(beanFactoryLocator).isNotNull();
assertThat(beanFactoryLocator.getBeanFactory()).isNull();
assertThat(beanFactoryLocator.getAssociatedBeanName()).isNull();
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).isNotNull();
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).isEmpty();
}
@Test
public void newInitializedBeanFactoryLocator() {
when(mockBeanFactory.getAliases(anyString())).thenReturn(new String[0]);
GemfireBeanFactoryLocator beanFactoryLocator = newBeanFactoryLocator(mockBeanFactory, "AssociatedBeanName");
assertThat(beanFactoryLocator).isNotNull();
assertThat(beanFactoryLocator.getBeanFactory()).isSameAs(mockBeanFactory);
assertThat(beanFactoryLocator.getAssociatedBeanName()).isEqualTo("AssociatedBeanName");
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).isNotNull();
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).hasSize(1);
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).containsAll(asSet("AssociatedBeanName"));
verify(mockBeanFactory, times(1)).getAliases(eq("AssociatedBeanName"));
}
@Test
public void newInitializedBeanFactoryLocatorWithNullBeanFactoryAndSpecifiedBeanName() {
GemfireBeanFactoryLocator beanFactoryLocator = newBeanFactoryLocator(null, "MyBeanName");
assertThat(beanFactoryLocator).isNotNull();
assertThat(beanFactoryLocator.getBeanFactory()).isNull();
assertThat(beanFactoryLocator.getAssociatedBeanName()).isEqualTo("MyBeanName");
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).isNotNull();
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).isEmpty();
}
@Test
public void newInitializedBeanFactoryLocatorWithNonNullBeanFactoryAndUnspecifiedBeanNameThrowsIllegalArgumentException() {
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("associatedBeanName must be specified when BeanFactory is not null");
newBeanFactoryLocator(mockBeanFactory, " ");
}
@Test
public void resolveBeanFactoryReturnsResolvedBeanFactory() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("MyBeanKey", mockBeanFactory);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES).hasSize(1);
assertThat(GemfireBeanFactoryLocator.resolveBeanFactory("MyBeanKey")).isSameAs(mockBeanFactory);
}
@Test
public void resolveBeanFactoryWithNoRegisteredBeanFactoriesAndAnyKeyReturnsNull() {
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES).isEmpty();
assertThat(GemfireBeanFactoryLocator.resolveBeanFactory("MyBeanKey")).isNull();
assertThat(GemfireBeanFactoryLocator.resolveBeanFactory("AnotherBeanKey")).isNull();
assertThat(GemfireBeanFactoryLocator.resolveBeanFactory("YetAnotherBeanKey")).isNull();
}
@Test
public void resolveBeanFactoryWithRegisteredBeanFactoriesAndUnknownKeyThrowsIllegalArgumentException() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("MyBeanKey", mockBeanFactory);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES).hasSize(1);
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("BeanFactory for key [UnknownKey] was not found");
GemfireBeanFactoryLocator.resolveBeanFactory("UnknownKey");
}
@Test
public void resolveSingleBeanFactoryWithNoRegisteredBeanFactoriesReturnsNull() {
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.isEmpty()).isTrue();
assertThat(GemfireBeanFactoryLocator.resolveSingleBeanFactory()).isNull();
}
@Test
public void resolveSingleBeanFactoryWhenSingleBeanFactoryIsRegisteredReturnsSingleBeanFactory() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("MyBeanKey", mockBeanFactory);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.size()).isEqualTo(1);
assertThat(GemfireBeanFactoryLocator.resolveSingleBeanFactory()).isSameAs(mockBeanFactory);
}
@Test
public void resolveSingleBeanFactoryWhenMultipleIdenticalBeanFactoriesAreRegisteredReturnsSingleBeanFactory() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("refOne", mockBeanFactory);
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("refTwo", mockBeanFactory);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.size()).isEqualTo(2);
assertThat(GemfireBeanFactoryLocator.resolveSingleBeanFactory()).isSameAs(mockBeanFactory);
}
@Test
public void resolveSingeBeanFactoryWhenMultipleDifferentBeanFactoriesAreRegisteredThrowsIllegalStateException() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("refOne", mockBeanFactory);
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("refTwo", mock(BeanFactory.class));
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.size()).isEqualTo(2);
exception.expect(IllegalStateException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("BeanFactory key must be specified when more than one BeanFactory [refOne, refTwo]"
+ " is registered");
GemfireBeanFactoryLocator.resolveSingleBeanFactory();
}
@Test
public void registerAliasesIsSuccessful() {
Set<String> aliases = asSet("aliasOne", "aliasTwo", "aliasThree");
GemfireBeanFactoryLocator.registerAliases(aliases, mockBeanFactory);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.size()).isEqualTo(3);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.keySet()).containsAll(aliases);
Set<BeanFactory> beanFactories = new HashSet<>(GemfireBeanFactoryLocator.BEAN_FACTORIES.values());
assertThat(beanFactories).hasSize(1);
assertThat(beanFactories).containsAll(asSet(mockBeanFactory));
}
@Test
public void registerAliasesWithEmptyAliasesAndNonNullBeanFactoryDoesNothing() {
GemfireBeanFactoryLocator.registerAliases(Collections.emptySet(), mockBeanFactory);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.isEmpty()).isTrue();
}
@Test
public void registerAliasesWithEmptyAliasesAndNullBeanFactoryDoesNothing() {
GemfireBeanFactoryLocator.registerAliases(Collections.emptySet(), null);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.isEmpty()).isTrue();
}
@Test
public void registerAliasesWithNonEmptyAliasesAndNullBeanFactoryThrowsIllegalArgumentException() {
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("BeanFactory must not be null when aliases are specified");
GemfireBeanFactoryLocator.registerAliases(asSet("aliasOne", "aliasTwo"), null);
}
@Test
public void registerAliasesWithNullAliasesHandlesNullAndDoesNothing() {
GemfireBeanFactoryLocator.registerAliases(null, null);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.isEmpty()).isTrue();
}
@Test
public void registerAliasesWhenIdenticalBeanFactoryReferencesAlreadyExistIsSuccessful() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("aliasTwo", mockBeanFactory);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.size()).isEqualTo(1);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.get("aliasTwo")).isSameAs(mockBeanFactory);
GemfireBeanFactoryLocator.registerAliases(asSet("aliasOne", "aliasTwo"), mockBeanFactory);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.size()).isEqualTo(2);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.get("aliasOne")).isSameAs(mockBeanFactory);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.get("aliasTwo")).isSameAs(mockBeanFactory);
}
@Test
public void registerAliasesWhenNonIdenticalBeanFactoryReferencesAlreadyExistThrowsIllegalArgumentException() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("aliasTwo", mockBeanFactory);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.size()).isEqualTo(1);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.get("aliasTwo")).isSameAs(mockBeanFactory);
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("BeanFactory reference already exists for key [aliasTwo]");
GemfireBeanFactoryLocator.registerAliases(asSet("aliasOne", "aliasTwo"), mock(BeanFactory.class));
}
@Test
public void unregisterAliasesRemovesAll() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("aliasOne", mockBeanFactory);
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("aliasTwo", mockBeanFactory);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.size()).isEqualTo(2);
GemfireBeanFactoryLocator.unregisterAliases(asSet("aliasOne", "aliasTwo"));
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.isEmpty()).isTrue();
}
@Test
public void unregisterAliasesRemovesPartial() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("aliasOne", mockBeanFactory);
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("aliasTwo", mockBeanFactory);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.size()).isEqualTo(2);
GemfireBeanFactoryLocator.unregisterAliases(asSet("aliasTwo"));
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.size()).isEqualTo(1);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.containsKey("aliasOne")).isTrue();
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.containsKey("aliasTwo")).isFalse();
}
@Test
public void unregisterAliasesRemovesNone() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("aliasOne", mockBeanFactory);
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("aliasTwo", mockBeanFactory);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.size()).isEqualTo(2);
GemfireBeanFactoryLocator.unregisterAliases(asSet("refOne", "refTwo"));
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.size()).isEqualTo(2);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.containsKey("aliasOne")).isTrue();
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.containsKey("aliasTwo")).isTrue();
}
@Test
public void afterPropertiesSetResolvesAndInitializesBeanNamesWithAliasesThenRegisterAliases() {
when(mockBeanFactory.getAliases(eq("AssociatedBeanName"))).thenReturn(new String[] { "aliasOne", "aliasTwo" });
GemfireBeanFactoryLocator beanFactoryLocator = newBeanFactoryLocator(mockBeanFactory, "AssociatedBeanName");
assertThat(beanFactoryLocator).isNotNull();
assertThat(beanFactoryLocator.getBeanFactory()).isSameAs(mockBeanFactory);
assertThat(beanFactoryLocator.getAssociatedBeanName()).isEqualTo("AssociatedBeanName");
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).isNotNull();
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).hasSize(3);
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases())
.containsAll(asSet("AssociatedBeanName", "aliasOne", "aliasTwo"));
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES).hasSize(3);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.keySet())
.containsAll(asSet("AssociatedBeanName", "aliasOne", "aliasTwo"));
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.get("AssociatedBeanName")).isSameAs(mockBeanFactory);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.get("aliasOne")).isSameAs(mockBeanFactory);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.get("aliasTwo")).isSameAs(mockBeanFactory);
verify(mockBeanFactory, times(1)).getAliases(eq("AssociatedBeanName"));
}
@Test
public void afterPropertiesSetUnableToResolveInitializeAndRegisterAliasesWithNullBeanFactory() {
GemfireBeanFactoryLocator beanFactoryLocator = newBeanFactoryLocator(null, "AssociatedBeanName");
assertThat(beanFactoryLocator).isNotNull();
assertThat(beanFactoryLocator.getBeanFactory()).isNull();
assertThat(beanFactoryLocator.getAssociatedBeanName()).isEqualTo("AssociatedBeanName");
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).isNotNull();
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).isEmpty();
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES).isEmpty();
}
@Test
public void destroyUnregistersOwningAliases() {
BeanFactory mockBeanFactoryTwo = mock(BeanFactory.class, "MockBeanFactoryTwo");
when(mockBeanFactory.getAliases(eq("AssociatedBeanName"))).thenReturn(new String[] { "aliasOne", "aliasTwo" });
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("refOne", mockBeanFactoryTwo);
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("refTwo", mockBeanFactoryTwo);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES).hasSize(2);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.keySet()).containsAll(asSet("refOne", "refTwo"));
GemfireBeanFactoryLocator beanFactoryLocator = newBeanFactoryLocator(mockBeanFactory, "AssociatedBeanName");
assertThat(beanFactoryLocator).isNotNull();
assertThat(beanFactoryLocator.getBeanFactory()).isSameAs(mockBeanFactory);
assertThat(beanFactoryLocator.getAssociatedBeanName()).isEqualTo("AssociatedBeanName");
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).isNotNull();
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).hasSize(3);
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).containsAll(
asSet("AssociatedBeanName", "aliasOne", "aliasTwo"));
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES).hasSize(5);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.keySet())
.containsAll(asSet("refOne", "refTwo", "AssociatedBeanName", "aliasOne", "aliasTwo"));
beanFactoryLocator.destroy();
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES).hasSize(2);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.keySet()).containsAll(asSet("refOne", "refTwo"));
verify(mockBeanFactory, times(1)).getAliases(eq("AssociatedBeanName"));
verifyZeroInteractions(mockBeanFactoryTwo);
}
@Test
public void useBeanFactoryWhenNoBeanFactoriesAreRegisteredThrowsIllegalStateException() {
exception.expect(IllegalStateException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage(UNINITIALIZED_BEAN_FACTORY_REFERENCE_MESSAGE);
newBeanFactoryLocator().useBeanFactory();
}
@Test
public void useBeanFactoryWhenSingleBeanFactoryIsRegisteredReturnsSingleBeanFactory() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("refOne", mockBeanFactory);
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("refTwo", mockBeanFactory);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.size()).isEqualTo(2);
assertThat(newBeanFactoryLocator().useBeanFactory()).isSameAs(mockBeanFactory);
}
@Test
public void useBeanFactoryWhenMultipleBeanFactoriesAreRegisteredThrowsIllegalStateException() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("refOne", mockBeanFactory);
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("refTwo", mock(BeanFactory.class, "MockBeanFactoryTwo"));
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES).hasSize(2);
exception.expect(IllegalStateException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("BeanFactory key must be specified when more than one BeanFactory [refOne, refTwo]"
+ " is registered");
newBeanFactoryLocator().useBeanFactory();
}
@Test
public void useBeanFactoryWhenMultipleBeanFactoriesAreRegisteredWithConfiguredKeyReturnsBeanFactory() {
BeanFactory mockBeanFactoryTwo = mock(BeanFactory.class, "MockBeanFactoryTwo");
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("refOne", mockBeanFactory);
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("refTwo", mockBeanFactoryTwo);
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES).hasSize(2);
assertThat(newBeanFactoryLocator(null, "refOne").useBeanFactory()).isSameAs(mockBeanFactory);
assertThat(newBeanFactoryLocator().withBeanName("refTwo").useBeanFactory()).isSameAs(mockBeanFactoryTwo);
}
@Test
public void useBeanFactoryWithKeyReturnsSpecificBeanFactory() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyOne", mockBeanFactory);
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyTwo", mock(BeanFactory.class, "MockBeanFactoryTwo"));
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES).hasSize(2);
assertThat(newBeanFactoryLocator().useBeanFactory("keyOne")).isSameAs(mockBeanFactory);
}
@Test
public void useBeanFactoryWithUnknownKeyThrowsIllegalArgumentException() {
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyOne", mockBeanFactory);
GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyTwo", mock(BeanFactory.class, "MockBeanFactoryTwo"));
assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.size()).isEqualTo(2);
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("BeanFactory for key [UnknownKey] was not found");
newBeanFactoryLocator().useBeanFactory("UnknownKey");
}
@Test
public void setAndGetBeanFactory() {
GemfireBeanFactoryLocator beanFactoryLocator = newBeanFactoryLocator();
assertThat(beanFactoryLocator).isNotNull();
assertThat(beanFactoryLocator.getBeanFactory()).isNull();
beanFactoryLocator.setBeanFactory(mockBeanFactory);
assertThat(beanFactoryLocator.getBeanFactory()).isSameAs(mockBeanFactory);
beanFactoryLocator.setBeanFactory(null);
assertThat(beanFactoryLocator.getBeanFactory()).isNull();
verifyZeroInteractions(mockBeanFactory);
}
@Test
public void setAndGetAssociatedBeanName() {
GemfireBeanFactoryLocator beanFactoryLocator = newBeanFactoryLocator(null, "AssociatedBeanName");
assertThat(beanFactoryLocator).isNotNull();
assertThat(beanFactoryLocator.getAssociatedBeanName()).isEqualTo("AssociatedBeanName");
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).isNotNull();
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).isEmpty();
beanFactoryLocator.setBeanName("TestBeanName");
assertThat(beanFactoryLocator.getAssociatedBeanName()).isEqualTo("TestBeanName");
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).isNotNull();
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).isEmpty();
beanFactoryLocator.setBeanName(null);
assertThat(beanFactoryLocator.getAssociatedBeanName()).isNull();
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).isNotNull();
assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).isEmpty();
}
@Test
public void withBeanNameIsSuccessful() {
GemfireBeanFactoryLocator beanFactoryLocator = newBeanFactoryLocator();
assertThat(beanFactoryLocator).isNotNull();
assertThat(beanFactoryLocator.getAssociatedBeanName()).isNull();
assertThat(beanFactoryLocator.withBeanName("MyBeanName")).isSameAs(beanFactoryLocator);
assertThat(beanFactoryLocator.getAssociatedBeanName()).isEqualTo("MyBeanName");
assertThat(beanFactoryLocator.withBeanName(null)).isSameAs(beanFactoryLocator);
assertThat(beanFactoryLocator.getAssociatedBeanName()).isNull();
}
}

View File

@@ -1,24 +1,23 @@
/*
* Copyright 2010-2013 the original author or authors.
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.data.gemfire;
package org.springframework.data.gemfire.support;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Properties;
@@ -31,26 +30,25 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.gemfire.function.sample.HelloFunctionExecution;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* The LazyWiringDeclarableSupportFunctionBasedIntegrationTest class is a test suite of test cases testing the contract
* and functionality of a GemFire Function implementing LazyWiringDeclarableSupport, defined using native GemFire
* configuration metadata (cache.xml).
* Integration test to test the functionality of a GemFire Function implementing the Spring Data GemFire
* {@link LazyWiringDeclarableSupport} class, defined using native GemFire configuration meta-data
* (i.e {@literal cache.xml}).
*
* @author John Blum
* @see org.junit.Test
* @see org.junit.runner.RunWith
* @see org.springframework.test.context.ContextConfiguration
* @see org.springframework.test.context.junit4.SpringJUnit4ClassRunner
* @see org.springframework.test.context.junit4.SpringRunner
* @since 1.7.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringRunner.class)
@ContextConfiguration
@SuppressWarnings("unused")
public class LazyWiringDeclarableSupportFunctionBasedIntegrationTest {
public class LazyWiringDeclarableSupportFunctionBasedIntegrationTests {
@Autowired
private Cache gemfireCache;
@@ -62,7 +60,7 @@ public class LazyWiringDeclarableSupportFunctionBasedIntegrationTest {
@BeforeClass
public static void setupBeforeClass() {
Cache gemfireCache = new CacheFactory()
.set("name", LazyWiringDeclarableSupportFunctionBasedIntegrationTest.class.getSimpleName())
.set("name", LazyWiringDeclarableSupportFunctionBasedIntegrationTests.class.getSimpleName())
.set("mcast-port", "0")
.set("log-level", "config")
.set("cache-xml-file", null)
@@ -80,15 +78,15 @@ public class LazyWiringDeclarableSupportFunctionBasedIntegrationTest {
@Test
public void helloGreeting() {
assertThat(helloFunctionExecution.hello(null), is(equalTo("Hello Everyone!")));
assertThat(helloFunctionExecution.hello(null)).isEqualTo("Hello Everyone!");
}
protected static abstract class FunctionAdaptor extends LazyWiringDeclarableSupport implements Function {
private final String id;
public FunctionAdaptor(final String id) {
Assert.hasText(id, "The Function ID must be specified!");
FunctionAdaptor(String id) {
Assert.hasText(id, "Function ID must be specified");
this.id = id;
}
@@ -113,6 +111,7 @@ public class LazyWiringDeclarableSupportFunctionBasedIntegrationTest {
}
}
@SuppressWarnings("all")
public static class HelloGemFireFunction extends FunctionAdaptor {
protected static final String ADDRESS_TO_PARAMETER = "hello.address.to";
@@ -167,5 +166,4 @@ public class LazyWiringDeclarableSupportFunctionBasedIntegrationTest {
return String.format(HELLO_GREETING, addressTo);
}
}
}

View File

@@ -1,31 +1,35 @@
/*
* Copyright 2010-2013 the original author or authors.
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.data.gemfire;
package org.springframework.data.gemfire.support;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.springframework.data.gemfire.support.WiringDeclarableSupport.TEMPLATE_BEAN_NAME_PROPERTY;
import java.util.Properties;
import javax.sql.DataSource;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
@@ -33,75 +37,72 @@ import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.gemfire.repository.sample.User;
import org.springframework.data.gemfire.test.support.DataSourceAdapter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
/**
* The LazyWiringDeclarableSupportIntegrationTest class is a test suite of integration test cases testing
* a LazyWiringDeclarableSupport object/component's wiring configuration and initialization in
* a Spring container context.
* Integration tests for {@link LazyWiringDeclarableSupport}.
*
* @author John Blum
* @see org.junit.Test
* @see org.junit.runner.RunWith
* @see org.springframework.test.context.ContextConfiguration
* @see org.springframework.test.context.junit4.SpringJUnit4ClassRunner
* @see org.springframework.test.context.junit4.SpringRunner
* @since 1.3.4
*/
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringRunner.class)
@ContextConfiguration
@SuppressWarnings("unused")
public class LazyWiringDeclarableSupportIntegrationTest {
public class LazyWiringDeclarableSupportIntegrationTests {
@Rule
public ExpectedException exception = ExpectedException.none();
@Autowired
private ApplicationContext applicationContext;
protected static Properties createParameters(final String parameter, final String value) {
private static Properties createParameters(String parameter, String value) {
Properties parameters = new Properties();
parameters.setProperty(parameter, value);
return parameters;
}
@Test
public void testWiring() {
public void autoWiringSuccessful() {
TestDeclarable declarable = new TestDeclarable();
declarable.init(createParameters("testParam", "testValue"));
declarable.onApplicationEvent(new ContextRefreshedEvent(applicationContext));
declarable.assertInitialized();
assertNull(declarable.getDataSource());
assertNotNull(declarable.getUser());
assertEquals("supertool", declarable.getUser().getUsername());
assertThat(declarable.getDataSource()).isNull();
assertThat(declarable.getUser()).isNotNull();
assertThat(declarable.getUser().getUsername()).isEqualTo("supertool");
}
@Test
public void testWiringWithBeanTemplate() {
public void autoWiringWithBeanTemplateSuccessful() {
TestDeclarable declarable = new TestDeclarable();
declarable.init(createParameters(LazyWiringDeclarableSupport.BEAN_NAME_PARAMETER, "declarableTemplateBean"));
declarable.init(createParameters(TEMPLATE_BEAN_NAME_PROPERTY, "declarableTemplateBean"));
declarable.onApplicationEvent(new ContextRefreshedEvent(applicationContext));
declarable.assertInitialized();
assertNotNull(declarable.getDataSource());
assertNotNull(declarable.getUser());
assertEquals("supertool", declarable.getUser().getUsername());
assertThat(declarable.getDataSource()).isNotNull();
assertThat(declarable.getUser()).isNotNull();
assertThat(declarable.getUser().getUsername()).isEqualTo("supertool");
}
@Test(expected = IllegalArgumentException.class)
public void testWiringWithNonExistingBeanTemplate() {
@Test
public void autoWiringWithNonExistingBeanTemplateThrowsIllegalArgumentException() {
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage(startsWith(
"Cannot find bean with name [nonExistingBeanTemplate]"));
TestDeclarable declarable = new TestDeclarable();
try {
declarable.init(createParameters(LazyWiringDeclarableSupport.BEAN_NAME_PARAMETER,
"nonExistingBeanTemplate"));
declarable.onApplicationEvent(new ContextRefreshedEvent(applicationContext));
}
catch (IllegalArgumentException expected) {
assertTrue(expected.getMessage().startsWith(
"No bean with name 'nonExistingBeanTemplate' was found in the Spring context"));
throw expected;
}
declarable.init(createParameters(TEMPLATE_BEAN_NAME_PROPERTY, "nonExistingBeanTemplate"));
declarable.onApplicationEvent(new ContextRefreshedEvent(applicationContext));
}
protected static final class TestDataSource extends DataSourceAdapter {
@@ -114,18 +115,17 @@ public class LazyWiringDeclarableSupportIntegrationTest {
@Autowired
private User user;
public final void setDataSource(final DataSource dataSource) {
public final void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
protected DataSource getDataSource() {
DataSource getDataSource() {
return dataSource;
}
protected User getUser() {
Assert.state(user != null, "A reference to the User was not properly configured!");
Assert.state(user != null, "A reference to the User was not properly configured");
return user;
}
}
}

View File

@@ -1,32 +1,35 @@
/*
* Copyright 2010-2013 the original author or authors.
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.data.gemfire;
package org.springframework.data.gemfire.support;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.data.gemfire.support.GemfireBeanFactoryLocator.newBeanFactoryLocator;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -40,33 +43,31 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.gemfire.support.SpringContextBootstrappingInitializer;
/**
* The LazyWiringDeclarableSupportTest class is a test suite of test cases testing the contract and functionality
* of the LazyWiringDeclarableSupport class. This test class focuses on testing isolated units of functionality
* in the Declarable class directly, mocking any dependencies as appropriate, in order for the class to uphold
* it's contract.
* Unit tests for {@link LazyWiringDeclarableSupport}.
*
* @author John Blum
* @see org.junit.Rule
* @see org.junit.Test
* @see org.mockito.Mockito
* @see org.springframework.data.gemfire.LazyWiringDeclarableSupport
* @see org.springframework.beans.factory.BeanFactory
* @see org.springframework.data.gemfire.support.GemfireBeanFactoryLocator
* @see org.springframework.data.gemfire.support.LazyWiringDeclarableSupport
* @since 1.3.4
*/
public class LazyWiringDeclarableSupportTest {
public class LazyWiringDeclarableSupportUnitTests {
@Rule
public ExpectedException expectedException = ExpectedException.none();
public ExpectedException exception = ExpectedException.none();
protected static void assertParameters(Properties parameters, String expectedKey, String expectedValue) {
private static void assertParameters(Properties parameters, String expectedKey, String expectedValue) {
assertThat(parameters, is(notNullValue()));
assertThat(parameters.containsKey(expectedKey), is(true));
assertThat(parameters.getProperty(expectedKey), is(equalTo(expectedValue)));
}
protected static Properties createParameters(final String parameter, final String value) {
private static Properties createParameters(String parameter, String value) {
Properties parameters = new Properties();
parameters.setProperty(parameter, value);
return parameters;
@@ -97,10 +98,10 @@ public class LazyWiringDeclarableSupportTest {
};
try {
expectedException.expect(IllegalStateException.class);
expectedException.expectCause(is(nullValue(Throwable.class)));
expectedException.expectMessage(String.format(
"This Declarable object (%1$s) has not been properly configured and initialized",
exception.expect(IllegalStateException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage(String.format(
"This Declarable object [%s] has not been properly configured and initialized",
declarable.getClass().getName()));
declarable.assertInitialized();
@@ -125,17 +126,18 @@ public class LazyWiringDeclarableSupportTest {
@Test
public void assertUninitializedWhenInitialized() {
LazyWiringDeclarableSupport declarable = new TestLazyWiringDeclarableSupport() {
@Override protected boolean isInitialized() {
@Override
protected boolean isInitialized() {
return true;
}
};
try {
expectedException.expect(IllegalStateException.class);
expectedException.expectCause(is(nullValue(Throwable.class)));
expectedException.expectMessage(String.format(
"This Declarable object (%1$s) has already been configured and initialized",
declarable.getClass().getName()));
exception.expect(IllegalStateException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage(String.format(
"This Declarable object [%s] has already been configured and initialized",
declarable.getClass().getName()));
declarable.assertUninitialized();
}
@@ -189,25 +191,6 @@ public class LazyWiringDeclarableSupportTest {
assertThat(declarable.isNotInitialized(), is(true));
}
@Test
public void locateBeanFactory() {
BeanFactory mockBeanFactory = mock(BeanFactory.class, "MockBeanFactory");
GemfireBeanFactoryLocator locator = new GemfireBeanFactoryLocator();
locator.setBeanName("MockBeanFactory");
locator.setBeanFactory(mockBeanFactory);
try {
locator.afterPropertiesSet();
assertThat(new TestLazyWiringDeclarableSupport().locateBeanFactory(null), is(sameInstance(mockBeanFactory)));
}
finally {
locator.destroy();
}
}
@Test
public void nullSafeGetParametersWithNullReference() {
LazyWiringDeclarableSupport declarable = new TestLazyWiringDeclarableSupport();
@@ -227,11 +210,8 @@ public class LazyWiringDeclarableSupportTest {
@Test
public void onApplicationEvent() {
ConfigurableApplicationContext mockApplicationContext = mock(ConfigurableApplicationContext.class,
"MockConfigurableApplicationContext");
ConfigurableListableBeanFactory mockBeanFactory = mock(ConfigurableListableBeanFactory.class,
"MockConfigurableListableBeanFactory");
ConfigurableApplicationContext mockApplicationContext = mock(ConfigurableApplicationContext.class);
ConfigurableListableBeanFactory mockBeanFactory = mock(ConfigurableListableBeanFactory.class);
when(mockApplicationContext.getBeanFactory()).thenReturn(mockBeanFactory);
@@ -241,7 +221,7 @@ public class LazyWiringDeclarableSupportTest {
@Override protected void doPostInit(final Properties parameters) {
super.doPostInit(parameters);
assertInitialized();
LazyWiringDeclarableSupportTest.assertParameters(parameters, "param", "value");
LazyWiringDeclarableSupportUnitTests.assertParameters(parameters, "param", "value");
doPostInitCalled.set(true);
}
};
@@ -269,13 +249,13 @@ public class LazyWiringDeclarableSupportTest {
LazyWiringDeclarableSupport declarable = new TestLazyWiringDeclarableSupport();
try {
ContextRefreshedEvent mockContextRefreshedEvent = mock(ContextRefreshedEvent.class, "MockContextRefreshedEvent");
ContextRefreshedEvent mockContextRefreshedEvent = mock(ContextRefreshedEvent.class);
when(mockContextRefreshedEvent.getApplicationContext()).thenReturn(null);
expectedException.expect(IllegalArgumentException.class);
expectedException.expectCause(is(nullValue(Throwable.class)));
expectedException.expectMessage("The Spring ApplicationContext (null) must be an instance of ConfigurableApplicationContext");
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("The Spring ApplicationContext [null] must be an instance of ConfigurableApplicationContext");
declarable.onApplicationEvent(mockContextRefreshedEvent);
}
@@ -290,11 +270,8 @@ public class LazyWiringDeclarableSupportTest {
@Test
public void fullLifecycleOnApplicationEventToDestroy() throws Exception {
ConfigurableApplicationContext mockApplicationContext = mock(ConfigurableApplicationContext.class,
"MockConfigurableApplicationContext");
ConfigurableListableBeanFactory mockBeanFactory = mock(ConfigurableListableBeanFactory.class,
"MockConfigurableListableBeanFactory");
ConfigurableApplicationContext mockApplicationContext = mock(ConfigurableApplicationContext.class);
ConfigurableListableBeanFactory mockBeanFactory = mock(ConfigurableListableBeanFactory.class);
when(mockApplicationContext.getBeanFactory()).thenReturn(mockBeanFactory);
@@ -304,7 +281,7 @@ public class LazyWiringDeclarableSupportTest {
@Override protected void doPostInit(final Properties parameters) {
super.doPostInit(parameters);
assertInitialized();
LazyWiringDeclarableSupportTest.assertParameters(parameters, "param", "value");
LazyWiringDeclarableSupportUnitTests.assertParameters(parameters, "param", "value");
doPostInitCalled.set(true);
}
};
@@ -349,28 +326,27 @@ public class LazyWiringDeclarableSupportTest {
@Test
public void initThenOnApplicationEventThenInitWhenInitialized() {
BeanFactory mockBeanFactory = mock(BeanFactory.class, "MockBeanFactory");
BeanFactory mockBeanFactory = mock(BeanFactory.class);
ConfigurableApplicationContext mockApplicationContext = mock(ConfigurableApplicationContext.class, "MockApplicationContext");
ConfigurableApplicationContext mockApplicationContext = mock(ConfigurableApplicationContext.class);
ConfigurableListableBeanFactory mockConfigurableListableBeanFactory = mock(ConfigurableListableBeanFactory.class,
"MockConfigurableListableBeanFactory");
ConfigurableListableBeanFactory mockConfigurableListableBeanFactory =
mock(ConfigurableListableBeanFactory.class);
when(mockApplicationContext.getBeanFactory()).thenReturn(mockConfigurableListableBeanFactory);
when(mockBeanFactory.getAliases(anyString())).thenReturn(new String[0]);
GemfireBeanFactoryLocator locator = new GemfireBeanFactoryLocator();
locator.setBeanName("MockBeanFactory");
locator.setBeanFactory(mockBeanFactory);
GemfireBeanFactoryLocator locator = newBeanFactoryLocator(mockBeanFactory, "MockBeanFactory");
final AtomicBoolean doPostInitCalled = new AtomicBoolean(false);
final AtomicReference<String> expectedKey = new AtomicReference<String>("testParam");
final AtomicReference<String> expectedValue = new AtomicReference<String>("testValue");
final AtomicReference<String> expectedKey = new AtomicReference<>("testParam");
final AtomicReference<String> expectedValue = new AtomicReference<>("testValue");
TestLazyWiringDeclarableSupport declarable = new TestLazyWiringDeclarableSupport() {
@Override protected void doPostInit(final Properties parameters) {
super.doPostInit(parameters);
assertInitialized();
LazyWiringDeclarableSupportTest.assertParameters(parameters, expectedKey.get(), expectedValue.get());
LazyWiringDeclarableSupportUnitTests.assertParameters(parameters, expectedKey.get(), expectedValue.get());
doPostInitCalled.set(true);
}
};
@@ -394,7 +370,7 @@ public class LazyWiringDeclarableSupportTest {
doPostInitCalled.set(false);
declarable.onApplicationEvent(new ContextRefreshedEvent(mockApplicationContext));
declarable.assertBeanFactory(mockBeanFactory);
declarable.assertBeanFactory(mockConfigurableListableBeanFactory);
declarable.assertParameters(parameters);
assertThat(declarable.isInitialized(), is(true));
@@ -421,29 +397,26 @@ public class LazyWiringDeclarableSupportTest {
}
}
protected static class TestLazyWiringDeclarableSupport extends LazyWiringDeclarableSupport {
private static class TestLazyWiringDeclarableSupport extends LazyWiringDeclarableSupport {
private BeanFactory actualBeanFactory;
private Properties actualParameters;
protected void assertBeanFactory(final BeanFactory expectedBeanFactory) {
assertThat(actualBeanFactory, is(sameInstance(expectedBeanFactory)));
private void assertBeanFactory(final BeanFactory expectedBeanFactory) {
assertThat(this.actualBeanFactory, is(sameInstance(expectedBeanFactory)));
}
protected void assertParameters(final Properties expectedParameters) {
assertThat(actualParameters, is(equalTo(expectedParameters)));
private void assertParameters(final Properties expectedParameters) {
assertThat(this.actualParameters, is(equalTo(expectedParameters)));
}
@Override
void doInit(final BeanFactory beanFactory, final Properties parameters) {
if (!isInitialized()) {
this.actualBeanFactory = beanFactory;
initialized = true;
}
void doInit(BeanFactory beanFactory, Properties parameters) {
this.actualBeanFactory = beanFactory;
this.actualParameters = parameters;
this.initialized = true;
doPostInit(parameters);
}
}
}

View File

@@ -47,7 +47,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.gemfire.LazyWiringDeclarableSupport;
import org.springframework.data.gemfire.config.xml.GemfireConstants;
import org.springframework.data.gemfire.repository.sample.User;
import org.springframework.data.gemfire.support.sample.TestUserDao;
@@ -62,7 +61,7 @@ import org.springframework.util.Assert;
* @author John Blum
* @see org.junit.Test
* @see org.springframework.context.ConfigurableApplicationContext
* @see org.springframework.data.gemfire.LazyWiringDeclarableSupport
* @see LazyWiringDeclarableSupport
* @see org.springframework.data.gemfire.support.SpringContextBootstrappingInitializer
* @see org.apache.geode.cache.Cache
* @see org.apache.geode.cache.CacheFactory

View File

@@ -118,7 +118,7 @@ public class SpringContextBootstrappingInitializerTest {
@Test
public void getUninitializedApplicationContext() {
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("The Spring ApplicationContext was not configured and initialized properly!");
expectedException.expectMessage("A Spring ApplicationContext was not configured and initialized properly");
expectedException.expectCause(is(nullValue(Throwable.class)));
SpringContextBootstrappingInitializer.getApplicationContext();
@@ -152,7 +152,7 @@ public class SpringContextBootstrappingInitializerTest {
expectedException.expect(IllegalStateException.class);
expectedException.expectCause(is(nullValue(Throwable.class)));
expectedException.expectMessage("The Spring ApplicationContext has already been initialized!");
expectedException.expectMessage("A Spring ApplicationContext has already been initialized");
try {
SpringContextBootstrappingInitializer.applicationContext = mockApplicationContext;
@@ -267,7 +267,7 @@ public class SpringContextBootstrappingInitializerTest {
public void initApplicationContextWithNull() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectCause(is(nullValue(Throwable.class)));
expectedException.expectMessage("The ConfigurableApplicationContext reference must not be null");
expectedException.expectMessage("ConfigurableApplicationContext must not be null");
new SpringContextBootstrappingInitializer().initApplicationContext(null);
}
@@ -287,7 +287,7 @@ public class SpringContextBootstrappingInitializerTest {
public void refreshApplicationContextWithNull() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectCause(is(nullValue(Throwable.class)));
expectedException.expectMessage("The ConfigurableApplicationContext reference must not be null");
expectedException.expectMessage("ConfigurableApplicationContext must not be null");
new SpringContextBootstrappingInitializer().refreshApplicationContext(null);
}
@@ -301,7 +301,7 @@ public class SpringContextBootstrappingInitializerTest {
assertThat(new SpringContextBootstrappingInitializer()
.registerAnnotatedClasses(mockApplicationContext, annotatedClasses),
is(sameInstance((ConfigurableApplicationContext) mockApplicationContext)));
is(sameInstance(mockApplicationContext)));
verify(mockApplicationContext, times(1)).register(annotatedClasses);
}
@@ -313,7 +313,7 @@ public class SpringContextBootstrappingInitializerTest {
assertThat(new SpringContextBootstrappingInitializer().registerAnnotatedClasses(mockApplicationContext,
new Class<?>[0]),
is(sameInstance((ConfigurableApplicationContext) mockApplicationContext)));
is(sameInstance(mockApplicationContext)));
verify(mockApplicationContext, never()).register(any(Class[].class));
}
@@ -335,7 +335,7 @@ public class SpringContextBootstrappingInitializerTest {
String[] basePackages = { "org.example.app", "org.example.plugins" };
assertThat(new SpringContextBootstrappingInitializer().scanBasePackages(mockApplicationContext, basePackages),
is(sameInstance((ConfigurableApplicationContext) mockApplicationContext)));
is(sameInstance(mockApplicationContext)));
verify(mockApplicationContext, times(1)).scan(basePackages);
}
@@ -346,7 +346,7 @@ public class SpringContextBootstrappingInitializerTest {
"MockApplicationContext");
assertThat(new SpringContextBootstrappingInitializer().scanBasePackages(mockApplicationContext, null),
is(sameInstance((ConfigurableApplicationContext) mockApplicationContext)));
is(sameInstance(mockApplicationContext)));
verify(mockApplicationContext, never()).scan(any(String[].class));
}
@@ -368,7 +368,7 @@ public class SpringContextBootstrappingInitializerTest {
SpringContextBootstrappingInitializer.setBeanClassLoader(Thread.currentThread().getContextClassLoader());
assertThat(new SpringContextBootstrappingInitializer().setClassLoader(mockApplicationContext),
is(sameInstance((ConfigurableApplicationContext) mockApplicationContext)));
is(sameInstance(mockApplicationContext)));
verify(mockApplicationContext, times(1)).setClassLoader(eq(Thread.currentThread().getContextClassLoader()));
}
@@ -392,7 +392,7 @@ public class SpringContextBootstrappingInitializerTest {
SpringContextBootstrappingInitializer.setBeanClassLoader(null);
assertThat(new SpringContextBootstrappingInitializer().setClassLoader(mockApplicationContext),
is(sameInstance((ConfigurableApplicationContext) mockApplicationContext)));
is(sameInstance(mockApplicationContext)));
verify(mockApplicationContext, never()).setClassLoader(any(ClassLoader.class));
}
@@ -606,8 +606,9 @@ public class SpringContextBootstrappingInitializerTest {
return mockLog;
}
@Override protected ConfigurableApplicationContext createApplicationContext(final String[] basePackages,
final String[] configLocations) {
@Override protected ConfigurableApplicationContext createApplicationContext(String[] basePackages,
String[] configLocations) {
throw new IllegalStateException("TEST");
}
};
@@ -949,5 +950,4 @@ public class SpringContextBootstrappingInitializerTest {
return this.name;
}
}
}

View File

@@ -0,0 +1,108 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.data.gemfire.support;
import static org.assertj.core.api.Assertions.assertThat;
import javax.annotation.Resource;
import org.apache.geode.cache.CacheLoader;
import org.apache.geode.cache.CacheLoaderException;
import org.apache.geode.cache.DataPolicy;
import org.apache.geode.cache.LoaderHelper;
import org.apache.geode.cache.Region;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Integration test for {@link WiringDeclarableSupport} and {@link GemfireBeanFactoryLocator}.
*
* @author Costin Leau
* @author John Blum
* @see org.junit.Test
* @see lombok
* @see org.apache.geode.cache.CacheLoader
* @see org.springframework.beans.factory.BeanFactory
* @see org.springframework.data.gemfire.support.GemfireBeanFactoryLocator
* @see org.springframework.data.gemfire.support.WiringDeclarableSupport
* @see org.springframework.test.context.ContextConfiguration
* @see org.springframework.test.context.junit4.SpringRunner
*/
@RunWith(SpringRunner.class)
@ContextConfiguration
public class WiringDeclarableSupportIntegrationTests {
@Autowired
@SuppressWarnings("unused")
private BeanFactory beanFactory;
@Resource(name = "Example")
@SuppressWarnings("unused")
private Region<String, String> example;
private void assertRegion(Region<?, ?> region, String name, DataPolicy dataPolicy) {
assertThat(region).isNotNull();
assertThat(region.getName()).isEqualTo(name);
assertThat(region.getFullPath()).isEqualTo(String.format("%1$s%2$s", Region.SEPARATOR, name));
assertThat(region.getAttributes()).isNotNull();
assertThat(region.getAttributes().getDataPolicy()).isEqualTo(dataPolicy);
}
@Test
public void declarableObjectAutoWiredSuccessfully() throws Exception {
assertThat(beanFactory.containsBean("testBean")).isTrue();
assertRegion(example, "Example", DataPolicy.NORMAL);
CacheLoader testCacheLoader = example.getAttributes().getCacheLoader();
assertThat(testCacheLoader).isInstanceOf(TestCacheLoader.class);
assertThat(((TestCacheLoader) testCacheLoader).getBeanFactory()).isSameAs(beanFactory);
assertThat(((TestCacheLoader) testCacheLoader).getPropertyOne()).isEqualTo(beanFactory.getBean("testBean"));
assertThat(((TestCacheLoader) testCacheLoader).getPropertyTwo()).isEqualTo("GoodBye");
}
@Data
@NoArgsConstructor
public static class TestBean {
private String name;
}
@Data
@NoArgsConstructor
public static class TestCacheLoader extends WiringDeclarableSupport implements CacheLoader<String, String> {
private Object propertyOne;
private String propertyTwo;
/**
* @inheritDoc
*/
@Override
public String load(LoaderHelper<String, String> helper) throws CacheLoaderException {
return helper.getKey();
}
}
}

View File

@@ -30,7 +30,6 @@ public class MockCacheFactoryBean extends CacheFactoryBean {
setUseBeanFactoryLocator(false);
if (cacheFactoryBean != null) {
this.beanFactoryLocator = cacheFactoryBean.getBeanFactoryLocator();
setBeanClassLoader(cacheFactoryBean.getBeanClassLoader());
setBeanFactory(cacheFactoryBean.getBeanFactory());
setBeanName(cacheFactoryBean.getBeanName());
@@ -56,6 +55,7 @@ public class MockCacheFactoryBean extends CacheFactoryBean {
setSearchTimeout(cacheFactoryBean.getSearchTimeout());
setTransactionListeners(cacheFactoryBean.getTransactionListeners());
setTransactionWriter(cacheFactoryBean.getTransactionWriter());
setUseBeanFactoryLocator(cacheFactoryBean.isUseBeanFactoryLocator());
}
}

View File

@@ -122,6 +122,37 @@ public class SpringUtilsUnitTests {
assertThat(SpringUtils.equalsIgnoreNull("nil", "null")).isFalse();
}
@Test
public void nullOrEqualsWithNullIsTrue() {
assertThat(SpringUtils.nullOrEquals(null, "test")).isTrue();
}
@Test
public void nullOrEqualsWithEqualObjectsIsTrue() {
assertThat(SpringUtils.nullOrEquals("test", "test")).isTrue();
}
@Test
public void nullOrEqualsWithUnequalObjectsIsFalse() {
assertThat(SpringUtils.nullOrEquals("test", "mock")).isFalse();
}
@Test
public void nullSafeEqualsWithEqualObjectsIsTrue() {
assertThat(SpringUtils.nullSafeEquals("test", "test")).isTrue();
}
@Test
public void nullSafeEqualsWithUnequalObjectsIsFalse() {
assertThat(SpringUtils.nullSafeEquals("test", "mock")).isFalse();
}
@Test
public void nullSafeEqualsWithNullObjectsIsFalse() {
assertThat(SpringUtils.nullSafeEquals(null, "test")).isFalse();
assertThat(SpringUtils.nullSafeEquals("test", null)).isFalse();
}
@Test
public void dereferenceBean() {
assertThat(SpringUtils.dereferenceBean("example")).isEqualTo("&example");