From 20fb6af9a55dcdd03ae4295fe1201275ded77c1e Mon Sep 17 00:00:00 2001 From: John Blum Date: Thu, 22 Jul 2021 19:41:28 -0700 Subject: [PATCH] Remove use of the Hamcrest library. Replace JUnit Assertions with AssertJ. Resolves gh-296. --- spring-data-geode/pom.xml | 14 -- .../gemfire/IndexMaintenancePolicyType.java | 12 +- .../GemfireTemplateIntegrationTests.java | 5 +- ...lsTest.java => GemfireUtilsUnitTests.java} | 37 ++-- ...exMaintenancePolicyConverterUnitTests.java | 46 ++-- .../gemfire/IndexTypeConverterUnitTests.java | 46 ++-- .../InterestPolicyConverterUnitTests.java | 56 ++--- .../data/gemfire/ScopeConverterUnitTests.java | 52 +++-- .../cache/CallableCacheLoaderAdapterTest.java | 133 ++++++------ .../cache/GemfireCacheManagerUnitTests.java | 112 ++++++---- .../gemfire/cache/GemfireCacheUnitTests.java | 119 ++++++---- ...nterestResultPolicyConverterUnitTests.java | 48 +++-- .../gemfire/client/InterestUnitTests.java | 51 +++-- ...egionLookupBeanPostProcessorUnitTests.java | 84 ++++---- .../dao/GemfireDaoSupportUnitTests.java | 34 +-- .../EvictionActionConverterUnitTests.java | 56 ++--- .../EvictionPolicyConverterUnitTests.java | 51 +++-- .../ExpirationActionConverterUnitTests.java | 54 +++-- .../GemfirePersistentEntityUnitTests.java | 50 ++--- ...RegionsTest.java => RegionsUnitTests.java} | 80 +++---- .../cdi/CdiExtensionIntegrationTest.java | 41 ++-- .../cdi/GemfireRepositoryBeanTest.java | 116 +++++----- .../cdi/GemfireRepositoryExtensionTest.java | 74 +++---- .../repository/query/PredicatesUnitTests.java | 33 +-- ...fireRepositoryFactoryIntegrationTests.java | 72 +++---- .../lucene/LuceneAccessorUnitTests.java | 105 +++++---- .../LuceneServiceFactoryBeanUnitTests.java | 42 ++-- ...ptionEvictionPolicyConverterUnitTests.java | 46 ++-- .../support/ConnectionEndpointListTest.java | 203 +++++++++--------- .../support/DeclarableSupportUnitTests.java | 85 +++++--- .../GemfireBeanFactoryLocatorUnitTests.java | 181 +++++++++++----- .../LazyWiringDeclarableSupportUnitTests.java | 198 ++++++++++------- ...auncherCacheProviderIntegrationTests.java} | 31 ++- ...ServerLauncherCacheProviderUnitTests.java} | 42 ++-- .../gemfire/util/PropertiesBuilderTests.java | 188 ++++++++-------- .../wan/OrderPolicyConverterUnitTests.java | 45 ++-- 36 files changed, 1462 insertions(+), 1180 deletions(-) rename spring-data-geode/src/test/java/org/springframework/data/gemfire/{GemfireUtilsTest.java => GemfireUtilsUnitTests.java} (79%) rename spring-data-geode/src/test/java/org/springframework/data/gemfire/mapping/{RegionsTest.java => RegionsUnitTests.java} (75%) rename spring-data-geode/src/test/java/org/springframework/data/gemfire/support/{SpringServerLauncherCacheProviderIntegrationTest.java => SpringServerLauncherCacheProviderIntegrationTests.java} (80%) rename spring-data-geode/src/test/java/org/springframework/data/gemfire/support/{SpringServerLauncherCacheProviderTest.java => SpringServerLauncherCacheProviderUnitTests.java} (80%) diff --git a/spring-data-geode/pom.xml b/spring-data-geode/pom.xml index 38ca267f..8ac402d1 100644 --- a/spring-data-geode/pom.xml +++ b/spring-data-geode/pom.xml @@ -217,20 +217,6 @@ test - - org.hamcrest - hamcrest-core - ${hamcrest} - test - - - - org.hamcrest - hamcrest-library - ${hamcrest} - test - - org.iq80.snappy snappy diff --git a/spring-data-geode/src/main/java/org/springframework/data/gemfire/IndexMaintenancePolicyType.java b/spring-data-geode/src/main/java/org/springframework/data/gemfire/IndexMaintenancePolicyType.java index 82caf3ae..ff386e40 100644 --- a/spring-data-geode/src/main/java/org/springframework/data/gemfire/IndexMaintenancePolicyType.java +++ b/spring-data-geode/src/main/java/org/springframework/data/gemfire/IndexMaintenancePolicyType.java @@ -13,14 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire; import org.apache.geode.cache.AttributesFactory; import org.apache.geode.cache.RegionFactory; /** - * The IndexMaintenanceType enum is a enumerated type of GemFire Index maintenance update options. + * The {@link IndexMaintenancePolicyType} enum is a enumerated type of GemFire Index maintenance update options. * * @author John Blum * @see org.apache.geode.cache.AttributesFactory#setIndexMaintenanceSynchronous(boolean) @@ -30,6 +29,7 @@ import org.apache.geode.cache.RegionFactory; */ @SuppressWarnings("unused") public enum IndexMaintenancePolicyType { + SYNCHRONOUS, ASYNCHRONOUS; @@ -45,7 +45,8 @@ public enum IndexMaintenancePolicyType { * @see java.lang.String#equalsIgnoreCase(String) * @see #name() */ - public static IndexMaintenancePolicyType valueOfIgnoreCase(final String name) { + public static IndexMaintenancePolicyType valueOfIgnoreCase(String name) { + for (IndexMaintenancePolicyType indexMaintenancePolicyType : values()) { if (indexMaintenancePolicyType.name().equalsIgnoreCase(name)) { return indexMaintenancePolicyType; @@ -64,7 +65,7 @@ public enum IndexMaintenancePolicyType { * @see #setIndexMaintenance(org.apache.geode.cache.RegionFactory) */ @SuppressWarnings("deprecation") - public void setIndexMaintenance(final AttributesFactory attributesFactory) { + public void setIndexMaintenance(AttributesFactory attributesFactory) { attributesFactory.setIndexMaintenanceSynchronous(equals(SYNCHRONOUS)); } @@ -76,8 +77,7 @@ public enum IndexMaintenancePolicyType { * @throws java.lang.NullPointerException if the RegionFactory reference is null. * @see #setIndexMaintenance(org.apache.geode.cache.AttributesFactory) */ - public void setIndexMaintenance(final RegionFactory regionFactory) { + public void setIndexMaintenance(RegionFactory regionFactory) { regionFactory.setIndexMaintenanceSynchronous(equals(SYNCHRONOUS)); } - } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/GemfireTemplateIntegrationTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/GemfireTemplateIntegrationTests.java index f9c8f190..c67025d4 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/GemfireTemplateIntegrationTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/GemfireTemplateIntegrationTests.java @@ -16,8 +16,7 @@ package org.springframework.data.gemfire; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.junit.Assume.assumeThat; +import static org.assertj.core.api.Assumptions.assumeThat; import java.time.Instant; import java.util.ArrayList; @@ -190,7 +189,7 @@ public class GemfireTemplateIntegrationTests extends IntegrationTestsSupport { @Test public void containsKeyOnServer() { - assumeThat(CacheUtils.isClient(this.gemfireCache), is(true)); + assumeThat(CacheUtils.isClient(this.gemfireCache)).isTrue(); assertThat(this.usersTemplate.containsKeyOnServer(getKey(getUser("jackHandy")))).isTrue(); assertThat(this.usersTemplate.containsKeyOnServer("maxPayne")).isFalse(); diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/GemfireUtilsTest.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/GemfireUtilsUnitTests.java similarity index 79% rename from spring-data-geode/src/test/java/org/springframework/data/gemfire/GemfireUtilsTest.java rename to spring-data-geode/src/test/java/org/springframework/data/gemfire/GemfireUtilsUnitTests.java index e4589a90..bbc8663a 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/GemfireUtilsTest.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/GemfireUtilsUnitTests.java @@ -13,45 +13,42 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.util.Properties; +import org.junit.Test; + import org.apache.geode.cache.Cache; import org.apache.geode.cache.client.ClientCache; import org.apache.geode.distributed.DistributedSystem; -import org.junit.Test; - /** - * The GemfireUtilsTest class is a test suite of test cases testing the contract and functionality of the GemfireUtils - * abstract utility class. + * Unit Tests for {@link GemfireUtils}. * * @author John Blum * @see org.junit.Test * @see org.springframework.data.gemfire.GemfireUtils * @since 1.3.3 */ -public class GemfireUtilsTest { +public class GemfireUtilsUnitTests { @Test public void isClientWithClientIsTrue() { ClientCache mockClient = mock(ClientCache.class); - assertThat(GemfireUtils.isClient(mockClient), is(true)); + assertThat(GemfireUtils.isClient(mockClient)).isTrue(); - verifyZeroInteractions(mockClient); + verifyNoInteractions(mockClient); } @Test @@ -59,9 +56,9 @@ public class GemfireUtilsTest { Cache mockCache = mock(Cache.class); - assertThat(GemfireUtils.isClient(mockCache), is(false)); + assertThat(GemfireUtils.isClient(mockCache)).isFalse(); - verifyZeroInteractions(mockCache); + verifyNoInteractions(mockCache); } @Test @@ -79,7 +76,7 @@ public class GemfireUtilsTest { when(mockDistributedSystem.isConnected()).thenReturn(true); when(mockDistributedSystem.getProperties()).thenReturn(gemfireProperties); - assertThat(GemfireUtils.isDurable(mockClientCache), is(true)); + assertThat(GemfireUtils.isDurable(mockClientCache)).isTrue(); verify(mockClientCache, times(1)).getDistributedSystem(); verify(mockDistributedSystem, times(1)).isConnected(); @@ -101,7 +98,7 @@ public class GemfireUtilsTest { when(mockDistributedSystem.isConnected()).thenReturn(true); when(mockDistributedSystem.getProperties()).thenReturn(gemfireProperties); - assertThat(GemfireUtils.isDurable(mockClientCache), is(false)); + assertThat(GemfireUtils.isDurable(mockClientCache)).isFalse(); verify(mockClientCache, times(1)).getDistributedSystem(); verify(mockDistributedSystem, times(1)).isConnected(); @@ -118,7 +115,7 @@ public class GemfireUtilsTest { when(mockClientCache.getDistributedSystem()).thenReturn(mockDistributedSystem); when(mockDistributedSystem.isConnected()).thenReturn(false); - assertThat(GemfireUtils.isDurable(mockClientCache), is(false)); + assertThat(GemfireUtils.isDurable(mockClientCache)).isFalse(); verify(mockClientCache, times(1)).getDistributedSystem(); verify(mockDistributedSystem, times(1)).isConnected(); @@ -130,9 +127,9 @@ public class GemfireUtilsTest { Cache mockCache = mock(Cache.class); - assertThat(GemfireUtils.isPeer(mockCache), is(true)); + assertThat(GemfireUtils.isPeer(mockCache)).isTrue(); - verifyZeroInteractions(mockCache); + verifyNoInteractions(mockCache); } @Test @@ -140,8 +137,8 @@ public class GemfireUtilsTest { ClientCache mockClientCache = mock(ClientCache.class); - assertThat(GemfireUtils.isPeer(mockClientCache), is(false)); + assertThat(GemfireUtils.isPeer(mockClientCache)).isFalse(); - verifyZeroInteractions(mockClientCache); + verifyNoInteractions(mockClientCache); } } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/IndexMaintenancePolicyConverterUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/IndexMaintenancePolicyConverterUnitTests.java index 8393c10d..f616d44f 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/IndexMaintenancePolicyConverterUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/IndexMaintenancePolicyConverterUnitTests.java @@ -13,20 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** - * Unit tests for {@link IndexMaintenancePolicyConverter}. + * Unit Tests for {@link IndexMaintenancePolicyConverter}. * * @author John Blum * @see org.junit.Test @@ -36,9 +31,6 @@ import org.junit.rules.ExpectedException; */ public class IndexMaintenancePolicyConverterUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - private final IndexMaintenancePolicyConverter converter = new IndexMaintenancePolicyConverter(); @After @@ -48,37 +40,53 @@ public class IndexMaintenancePolicyConverterUnitTests { @Test public void convert() { + assertThat(converter.convert("asynchronous")).isEqualTo(IndexMaintenancePolicyType.ASYNCHRONOUS); assertThat(converter.convert("Synchronous")).isEqualTo(IndexMaintenancePolicyType.SYNCHRONOUS); } - @Test + @Test(expected = IllegalArgumentException.class) public void convertIllegalValue() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[sync] is not a valid IndexMaintenancePolicyType"); - converter.convert("sync"); + try { + converter.convert("sync"); + } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[sync] is not a valid IndexMaintenancePolicyType"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void setAsText() { + assertThat(converter.getValue()).isNull(); + converter.setAsText("aSynchronous"); + assertThat(converter.getValue()).isEqualTo(IndexMaintenancePolicyType.ASYNCHRONOUS); + converter.setAsText("synchrONoUS"); + assertThat(converter.getValue()).isEqualTo(IndexMaintenancePolicyType.SYNCHRONOUS); } - @Test + @Test(expected = IllegalArgumentException.class) public void setAsTextWithIllegalValue() { - try { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[async] is not a valid IndexMaintenancePolicyType"); + try { converter.setAsText("async"); } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[async] is not a valid IndexMaintenancePolicyType"); + assertThat(expected).hasNoCause(); + + throw expected; + } finally { assertThat(converter.getValue()).isNull(); } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/IndexTypeConverterUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/IndexTypeConverterUnitTests.java index 99b0d1d7..9d5f27ff 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/IndexTypeConverterUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/IndexTypeConverterUnitTests.java @@ -13,20 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** - * Unit tests for {@link IndexTypeConverter}. + * Unit Tests for {@link IndexTypeConverter}. * * @author John Blum * @see org.junit.Test @@ -36,9 +31,6 @@ import org.junit.rules.ExpectedException; */ public class IndexTypeConverterUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - private final IndexTypeConverter converter = new IndexTypeConverter(); @After @@ -48,6 +40,7 @@ public class IndexTypeConverterUnitTests { @Test public void convert() { + assertThat(converter.convert("FUNCTIONAL")).isEqualTo(IndexType.FUNCTIONAL); assertThat(converter.convert("hASh")).isEqualTo(IndexType.HASH); assertThat(converter.convert("hASH")).isEqualTo(IndexType.HASH); @@ -55,33 +48,48 @@ public class IndexTypeConverterUnitTests { assertThat(converter.convert("primary_KEY")).isEqualTo(IndexType.PRIMARY_KEY); } - @Test + @Test(expected = IllegalArgumentException.class) public void convertWithIllegalValue() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[function] is not a valid IndexType"); - converter.convert("function"); + try { + converter.convert("function"); + } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[function] is not a valid IndexType"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void setAsText() { + assertThat(converter.getValue()).isNull(); + converter.setAsText("HasH"); + assertThat(converter.getValue()).isEqualTo(IndexType.HASH); + converter.setAsText("key"); + assertThat(converter.getValue()).isEqualTo(IndexType.KEY); } - @Test + @Test(expected = IllegalArgumentException.class) public void setAsTextWithIllegalValue() { - try { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[invalid] is not a valid IndexType"); + try { converter.setAsText("invalid"); } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[invalid] is not a valid IndexType"); + assertThat(expected).hasNoCause(); + + throw expected; + } finally { assertThat(converter.getValue()).isNull(); } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/InterestPolicyConverterUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/InterestPolicyConverterUnitTests.java index ce074e18..8a432cc8 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/InterestPolicyConverterUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/InterestPolicyConverterUnitTests.java @@ -13,35 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; + +import org.junit.After; +import org.junit.Test; import org.apache.geode.cache.InterestPolicy; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - /** - * Unit tests for {@link InterestPolicyConverter}. + * Unit Tests for {@link InterestPolicyConverter}. * * @author John Blum * @see org.junit.Test - * @see org.springframework.data.gemfire.InterestPolicyConverter * @see org.apache.geode.cache.InterestPolicy + * @see org.springframework.data.gemfire.InterestPolicyConverter * @since 1.6.0 */ public class InterestPolicyConverterUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - - private InterestPolicyConverter converter = new InterestPolicyConverter(); + private final InterestPolicyConverter converter = new InterestPolicyConverter(); @After public void tearDown() { @@ -50,39 +42,55 @@ public class InterestPolicyConverterUnitTests { @Test public void convert() { + assertThat(converter.convert("all")).isEqualTo(InterestPolicy.ALL); assertThat(converter.convert("Cache_Content")).isEqualTo(InterestPolicy.CACHE_CONTENT); assertThat(converter.convert("CACHE_ConTent")).isEqualTo(InterestPolicy.CACHE_CONTENT); assertThat(converter.convert("ALL")).isEqualTo(InterestPolicy.ALL); } - @Test + @Test(expected = IllegalArgumentException.class) public void convertIllegalValue() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[invalid_value] is not a valid InterestPolicy"); - converter.convert("invalid_value"); + try { + converter.convert("invalid_value"); + } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[invalid_value] is not a valid InterestPolicy"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void setAsText() { + assertThat(converter.getValue()).isNull(); + converter.setAsText("aLl"); + assertThat(converter.getValue()).isEqualTo(InterestPolicy.ALL); + converter.setAsText("Cache_CoNTeNT"); + assertThat(converter.getValue()).isEqualTo(InterestPolicy.CACHE_CONTENT); } - @Test + @Test(expected = IllegalArgumentException.class) public void setAsTextWithInvalidValue() { - try { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[none] is not a valid InterestPolicy"); + try { converter.setAsText("none"); } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[none] is not a valid InterestPolicy"); + assertThat(expected).hasNoCause(); + + throw expected; + } finally { assertThat(converter.getValue()).isNull(); } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/ScopeConverterUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/ScopeConverterUnitTests.java index 1f2ee3cb..969f3cb8 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/ScopeConverterUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/ScopeConverterUnitTests.java @@ -13,22 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; + +import org.junit.After; +import org.junit.Test; import org.apache.geode.cache.Scope; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - /** - * Unit tests for {@link ScopeConverter}. + * Unit Tests for {@link ScopeConverter}. * * @author John Blum * @see org.junit.Test @@ -38,9 +33,6 @@ import org.junit.rules.ExpectedException; */ public class ScopeConverterUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - private final ScopeConverter converter = new ScopeConverter(); @After @@ -50,39 +42,55 @@ public class ScopeConverterUnitTests { @Test public void convert() { + assertThat(converter.convert("distributed-ACK")).isEqualTo(Scope.DISTRIBUTED_ACK); assertThat(converter.convert(" Distributed_NO-aCK")).isEqualTo(Scope.DISTRIBUTED_NO_ACK); assertThat(converter.convert("loCAL ")).isEqualTo(Scope.LOCAL); assertThat(converter.convert(" GLOBal ")).isEqualTo(Scope.GLOBAL); } - @Test + @Test(expected = IllegalArgumentException.class) public void convertIllegalValue() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[illegal-value] is not a valid Scope"); - converter.convert("illegal-value"); + try { + converter.convert("illegal-value"); + } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[illegal-value] is not a valid Scope"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void setAsText() { + assertThat(converter.getValue()).isNull(); + converter.setAsText("DisTributeD-nO_Ack"); + assertThat(converter.getValue()).isEqualTo(Scope.DISTRIBUTED_NO_ACK); + converter.setAsText("distributed-ack"); + assertThat(converter.getValue()).isEqualTo(Scope.DISTRIBUTED_ACK); } - @Test + @Test(expected = IllegalArgumentException.class) public void setAsTextWithIllegalValue() { - try { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[d!5tr!but3d-n0_@ck] is not a valid Scope"); + try { converter.setAsText("d!5tr!but3d-n0_@ck"); } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[d!5tr!but3d-n0_@ck] is not a valid Scope"); + assertThat(expected).hasNoCause(); + + throw expected; + } finally { assertThat(converter.getValue()).isNull(); } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/cache/CallableCacheLoaderAdapterTest.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/cache/CallableCacheLoaderAdapterTest.java index 70a44bc0..fab21e41 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/cache/CallableCacheLoaderAdapterTest.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/cache/CallableCacheLoaderAdapterTest.java @@ -14,15 +14,9 @@ * limitations under the License. * */ - package org.springframework.data.gemfire.cache; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -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.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; @@ -30,12 +24,9 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -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.invocation.InvocationOnMock; import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; @@ -44,14 +35,11 @@ import org.apache.geode.cache.LoaderHelper; import org.apache.geode.cache.Region; /** - * Unit tests to test the adaption of the {@link java.util.concurrent.Callable} - * into GemFire's {@link org.apache.geode.cache.CacheLoader} interface. + * Unit Tests to test the adaption of the {@link java.util.concurrent.Callable} + * into Apache Geode's {@link org.apache.geode.cache.CacheLoader} interface. * * @author John Blum - * @see org.junit.Rule * @see org.junit.Test - * @see org.junit.rules.ExpectedException - * @see org.junit.runner.RunWith * @see org.mockito.Mock * @see org.mockito.Mockito * @see org.mockito.junit.MockitoJUnitRunner @@ -67,9 +55,6 @@ public class CallableCacheLoaderAdapterTest { @Mock private CacheLoader mockCacheLoader; - @Rule - public ExpectedException exception = ExpectedException.none(); - @Mock private LoaderHelper mockLoaderHelper; @@ -79,115 +64,139 @@ public class CallableCacheLoaderAdapterTest { @Test public void constructCallableCacheLoaderAdapterWithArgumentKeyAndRegion() { CallableCacheLoaderAdapter instance = + new CallableCacheLoaderAdapter<>(mockCacheLoader, "key", mockRegion, "test"); - assertThat(instance, is(notNullValue())); - assertThat(instance.getCacheLoader(), is(sameInstance(mockCacheLoader))); - assertThat(instance.getKey(), is(equalTo("key"))); - assertThat(instance.getRegion(), is(sameInstance(mockRegion))); - assertThat(String.valueOf(instance.getArgument()), is(equalTo("test"))); + assertThat(instance).isNotNull(); + assertThat(instance.getCacheLoader()).isSameAs(mockCacheLoader); + assertThat(instance.getKey()).isEqualTo("key"); + assertThat(instance.getRegion()).isSameAs(mockRegion); + assertThat(String.valueOf(instance.getArgument())).isEqualTo("test"); } @Test public void constructCallableCacheLoaderAdapterWithKeyRegionAndNoArgument() { + CallableCacheLoaderAdapter instance = new CallableCacheLoaderAdapter<>(mockCacheLoader, "key", mockRegion); - assertThat(instance, is(notNullValue())); - assertThat(instance.getCacheLoader(), is(sameInstance(mockCacheLoader))); - assertThat(instance.getKey(), is(equalTo("key"))); - assertThat(instance.getRegion(), is(sameInstance(mockRegion))); - assertThat(instance.getArgument(), is(nullValue())); + assertThat(instance).isNotNull(); + assertThat(instance.getCacheLoader()).isSameAs(mockCacheLoader); + assertThat(instance.getKey()).isEqualTo("key"); + assertThat(instance.getRegion()).isSameAs(mockRegion); + assertThat(instance.getArgument()).isNull(); } @Test public void constructCallableCacheLoaderAdapterWithNoArgumentKeyOrRegion() { + CallableCacheLoaderAdapter instance = new CallableCacheLoaderAdapter<>(mockCacheLoader); - assertThat(instance, is(notNullValue())); - assertThat(instance.getCacheLoader(), is(sameInstance(mockCacheLoader))); - assertThat(instance.getKey(), is(nullValue())); - assertThat(instance.getRegion(), is(nullValue())); - assertThat(instance.getArgument(), is(nullValue())); + assertThat(instance).isNotNull(); + assertThat(instance.getCacheLoader()).isSameAs(mockCacheLoader); + assertThat(instance.getKey()).isNull(); + assertThat(instance.getRegion()).isNull(); + assertThat(instance.getArgument()).isNull(); } - @Test + @Test(expected = IllegalArgumentException.class) public void constructCallableCacheLoaderAdapterWithNullCacheLoader() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("CacheLoader must not be null"); - new CallableCacheLoaderAdapter<>(null); + try { + new CallableCacheLoaderAdapter<>(null); + } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("CacheLoader must not be null"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test @SuppressWarnings("unchecked") public void callDelegatesToLoad() throws Exception { + CallableCacheLoaderAdapter instance = new CallableCacheLoaderAdapter<>(mockCacheLoader, "key", mockRegion, "test"); - when(mockCacheLoader.load(any(LoaderHelper.class))).thenAnswer(new Answer() { - public String answer(final InvocationOnMock invocation) throws Throwable { - LoaderHelper loaderHelper = invocation.getArgument(0); + when(mockCacheLoader.load(any(LoaderHelper.class))).thenAnswer((Answer) invocation -> { - assertThat(loaderHelper, is(notNullValue())); - assertThat(loaderHelper.getArgument(), is(equalTo("test"))); - assertThat(loaderHelper.getKey(), is(equalTo("key"))); - assertThat(loaderHelper.getRegion(), is(sameInstance(mockRegion))); + LoaderHelper loaderHelper = invocation.getArgument(0); - return "mockValue"; - } + assertThat(loaderHelper).isNotNull(); + assertThat(loaderHelper.getArgument()).isEqualTo("test"); + assertThat(loaderHelper.getKey()).isEqualTo("key"); + assertThat(loaderHelper.getRegion()).isSameAs(mockRegion); + + return "mockValue"; }); - assertThat(instance.call(), is(equalTo("mockValue"))); + assertThat(instance.call()).isEqualTo("mockValue"); verify(mockCacheLoader, times(1)).load(isA(LoaderHelper.class)); } - @Test + @Test(expected = IllegalStateException.class) public void callThrowsIllegalStateExceptionForNullKey() throws Exception { + CallableCacheLoaderAdapter instance = new CallableCacheLoaderAdapter<>(mockCacheLoader, null, mockRegion); - assertThat(instance.getKey(), is(nullValue())); - assertThat(instance.getRegion(), is(sameInstance(mockRegion))); + assertThat(instance.getKey()).isNull(); + assertThat(instance.getRegion()).isSameAs(mockRegion); - exception.expect(IllegalStateException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("The key for which the value is loaded for cannot be null"); + try { + instance.call(); + } + catch (IllegalStateException expected) { - instance.call(); + assertThat(expected).hasMessage("The key for which the value is loaded for cannot be null"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void callThrowsIllegalStateExceptionForNullRegion() throws Exception { + CallableCacheLoaderAdapter instance = new CallableCacheLoaderAdapter<>(mockCacheLoader, "key", null); - assertThat(instance.getKey(), is(equalTo("key"))); - assertThat(instance.getRegion(), is(nullValue())); + assertThat(instance.getKey()).isEqualTo("key"); + assertThat(instance.getRegion()).isNull(); - exception.expect(IllegalStateException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("The Region to load cannot be null"); + try { + instance.call(); + } + catch (IllegalStateException expected) { - instance.call(); + assertThat(expected).hasMessage("The Region to load cannot be null"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void closeDelegatesToCacheLoaderClose() { + new CallableCacheLoaderAdapter<>(mockCacheLoader).close(); + verify(mockCacheLoader, times(1)).close(); } @Test public void loadDelegatesToCacheLoaderLoad() { + CallableCacheLoaderAdapter instance = new CallableCacheLoaderAdapter<>(mockCacheLoader); when(mockCacheLoader.load(eq(mockLoaderHelper))).thenReturn("test"); - assertThat(instance.load(mockLoaderHelper), is(equalTo("test"))); + assertThat(instance.load(mockLoaderHelper)).isEqualTo("test"); verify(mockCacheLoader, times(1)).load(eq(mockLoaderHelper)); } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/cache/GemfireCacheManagerUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/cache/GemfireCacheManagerUnitTests.java index fd7798ad..f2fca456 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/cache/GemfireCacheManagerUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/cache/GemfireCacheManagerUnitTests.java @@ -14,13 +14,9 @@ * limitations under the License. * */ - package org.springframework.data.gemfire.cache; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -35,9 +31,7 @@ import java.util.HashSet; import java.util.Set; 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.junit.MockitoJUnitRunner; @@ -59,36 +53,40 @@ import org.springframework.cache.Cache; @RunWith(MockitoJUnitRunner.class) public class GemfireCacheManagerUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - @Mock private GemFireCache mockGemFireCache; private GemfireCacheManager cacheManager; @Mock - private Region mockRegion; + private Region mockRegion; @Before public void setup() { cacheManager = new GemfireCacheManager(); } - protected Set asSet(T... elements) { - Set set = new HashSet(elements.length); + @SafeVarargs + private static Set asSet(T... elements) { + + Set set = new HashSet<>(elements.length); + Collections.addAll(set, elements); + return set; } - @SuppressWarnings("unchecked") - protected Region mockRegion(String name) { + private Region mockRegion(String name) { + Region mockRegion = mock(Region.class, name); + when(mockRegion.getName()).thenReturn(name); + return mockRegion; } - protected Region regionFor(Iterable> regions, String name) { + private Region regionFor(Iterable> regions, String name) { + for (Region region : regions) { if (region.getName().equals(name)) { return region; @@ -100,33 +98,46 @@ public class GemfireCacheManagerUnitTests { @Test public void assertGemFireCacheAvailableWithAvailableGemFireCacheIsSuccessful() { + when(mockGemFireCache.isClosed()).thenReturn(false); + assertThat(cacheManager.assertGemFireCacheAvailable(mockGemFireCache)).isSameAs(mockGemFireCache); + verify(mockGemFireCache, times(1)).isClosed(); verify(mockGemFireCache, times(1)).getName(); } - @Test + @Test(expected = IllegalStateException.class) public void assertGemFireCacheAvailableWithNullThrowsIllegalStateException() { - exception.expect(IllegalStateException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage(is(equalTo("A GemFire cache instance is required"))); - cacheManager.assertGemFireCacheAvailable(null); + try { + cacheManager.assertGemFireCacheAvailable(null); + } + catch (IllegalStateException expected) { + + assertThat(expected).hasMessage("A GemFire cache instance is required"); + assertThat(expected).hasNoCause(); + + throw expected; + } } - @Test + @Test(expected = IllegalStateException.class) public void assertGemFireCacheAvailableWithNamedClosedGemFireCacheThrowsIllegalStateException() { + when(mockGemFireCache.isClosed()).thenReturn(true); when(mockGemFireCache.getName()).thenReturn("Example"); try { - exception.expect(IllegalStateException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage(is(equalTo("GemFire cache [Example] has been closed"))); - cacheManager.assertGemFireCacheAvailable(mockGemFireCache); } + catch (IllegalStateException expected) { + + assertThat(expected).hasMessage("GemFire cache [Example] has been closed"); + assertThat(expected).hasNoCause(); + + throw expected; + } finally { verify(mockGemFireCache,times(1)).isClosed(); verify(mockGemFireCache, times(1)).getName(); @@ -135,39 +146,52 @@ public class GemfireCacheManagerUnitTests { @Test public void assertGemFireRegionAvailableWithAvailableGemFireRegionIsSuccessful() { + when(mockRegion.isDestroyed()).thenReturn(false); + assertThat(cacheManager.assertGemFireRegionAvailable(mockRegion, "Example")).isSameAs(mockRegion); + verify(mockRegion, times(1)).isDestroyed(); } - @Test + @Test(expected = IllegalStateException.class) public void assertGemFireRegionAvailableWithNullThrowIllegalStateException() { - exception.expect(IllegalStateException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage(is(equalTo("No Region for cache name [Example] was found"))); - cacheManager.assertGemFireRegionAvailable(null, "Example"); + try { + cacheManager.assertGemFireRegionAvailable(null, "Example"); + } + catch (IllegalStateException expected) { + + assertThat(expected).hasMessage("No Region for cache name [Example] was found"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void assertGemFireRegionAvailableWithDestroyedGemFireRegionThrowIllegalStateException() { + when(mockRegion.isDestroyed()).thenReturn(true); try { - exception.expect(IllegalStateException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage(is(equalTo("Region [Example] has been destroyed"))); - cacheManager.assertGemFireRegionAvailable(mockRegion, "Example"); } + catch (IllegalStateException expected) { + + assertThat(expected).hasMessage("Region [Example] has been destroyed"); + assertThat(expected).hasNoCause(); + + throw expected; + } finally { verify(mockRegion, times(1)).isDestroyed(); } } @Test - @SuppressWarnings("unchecked") public void loadCachesIsSuccessful() { + Set> regions = asSet(mockRegion("one"), mockRegion("two"), mockRegion("three")); cacheManager.setRegions(regions); @@ -185,6 +209,7 @@ public class GemfireCacheManagerUnitTests { @Test public void resolveRegionsReturnsGivenRegions() { + Set> regions = asSet(mockRegion("one"), mockRegion("two")); assertThat(cacheManager.resolveRegions(mockGemFireCache, regions, asSet("three", "four"))).isSameAs(regions); @@ -195,8 +220,9 @@ public class GemfireCacheManagerUnitTests { } @Test - @SuppressWarnings("unchecked") + @SuppressWarnings({ "rawtypes", "unchecked" }) public void resolveRegionsReturnsRegionsForCacheNamesOnly() { + Region mockRegionOne = mockRegion("one"); Region mockRegionTwo = mockRegion("two"); @@ -207,7 +233,7 @@ public class GemfireCacheManagerUnitTests { assertThat(regions).isNotNull(); assertThat(regions.size()).isEqualTo(2); - assertThat(regions).containsAll(this.>asSet(mockRegionOne, mockRegionTwo)); + assertThat(regions).containsAll(GemfireCacheManagerUnitTests.>asSet(mockRegionOne, mockRegionTwo)); assertThat(cacheManager.isDynamic()).isFalse(); verify(mockGemFireCache, times(1)).getRegion(eq("one")); @@ -217,6 +243,7 @@ public class GemfireCacheManagerUnitTests { @Test public void resolveRegionsReturnsGemFireCacheRootRegions() { + Set> rootRegions = asSet(mockRegion("one"), mockRegion("two")); when(mockGemFireCache.rootRegions()).thenReturn(rootRegions); @@ -244,8 +271,8 @@ public class GemfireCacheManagerUnitTests { } @Test - @SuppressWarnings("unchecked") public void regionForCacheNameReturnsRegion() { + when(mockGemFireCache.isClosed()).thenReturn(false); when(mockGemFireCache.getName()).thenReturn("regionForCacheNameReturnsRegion"); when(mockGemFireCache.getRegion(eq("Example"))).thenReturn(mockRegion); @@ -260,8 +287,9 @@ public class GemfireCacheManagerUnitTests { } @Test - @SuppressWarnings("unchecked") + @SuppressWarnings({ "rawtypes", "unchecked" }) public void getMissingCacheReturnsMissingCache() { + Region mockRegion = mockRegion("missing"); when(mockGemFireCache.getRegion(eq("missing"))).thenReturn(mockRegion); @@ -278,7 +306,8 @@ public class GemfireCacheManagerUnitTests { @Test public void getMissingCacheReturnsNull() { - cacheManager.setRegions(Collections.>singleton(mockRegion("one"))); + + cacheManager.setRegions(Collections.singleton(mockRegion("one"))); cacheManager.afterPropertiesSet(); assertThat(cacheManager.isDynamic()).isFalse(); @@ -287,6 +316,7 @@ public class GemfireCacheManagerUnitTests { @Test public void setAndGetCache() { + assertThat(cacheManager.getCache()).isNull(); cacheManager.setCache(mockGemFireCache); @@ -300,6 +330,7 @@ public class GemfireCacheManagerUnitTests { @Test public void setAndGetCacheNames() { + Set> regions = asSet(mockRegion("one"), mockRegion("two")); cacheManager.setRegions(regions); @@ -310,6 +341,7 @@ public class GemfireCacheManagerUnitTests { @Test public void setAndGetRegions() { + Set> regions = asSet(mockRegion("one"), mockRegion("two")); assertThat(cacheManager.getRegions()).isNull(); diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/cache/GemfireCacheUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/cache/GemfireCacheUnitTests.java index f5c94c85..ff76b1eb 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/cache/GemfireCacheUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/cache/GemfireCacheUnitTests.java @@ -14,28 +14,21 @@ * limitations under the License. * */ - package org.springframework.data.gemfire.cache; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.isA; -import static org.hamcrest.Matchers.nullValue; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; +import static org.assertj.core.internal.bytebuddy.matcher.ElementMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.util.concurrent.Callable; -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.junit.MockitoJUnitRunner; @@ -45,22 +38,20 @@ import org.apache.geode.cache.Region; import org.springframework.cache.Cache; /** - * Unit tests for {@link GemfireCache}. + * Unit Tests for {@link GemfireCache}. * * @author John Blum * @see org.junit.Test * @see org.mockito.Mock * @see org.mockito.junit.MockitoJUnitRunner - * @see GemfireCache * @see org.apache.geode.cache.Region + * @see org.springframework.data.gemfire.cache.GemfireCache * @since 1.9.0 */ @RunWith(MockitoJUnitRunner.class) +@SuppressWarnings("rawtypes") public class GemfireCacheUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - @Mock private Callable mockCallable; @@ -68,44 +59,60 @@ public class GemfireCacheUnitTests { private Region mockRegion; @Test + @SuppressWarnings("unchecked") public void wrapIsSuccessful() { + GemfireCache gemfireCache = GemfireCache.wrap(mockRegion); assertThat(gemfireCache).isNotNull(); assertThat(gemfireCache.getNativeCache()).isEqualTo(mockRegion); } - @Test + @Test(expected = IllegalArgumentException.class) public void constructGemfireCacheWithNullRegion() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage(is(equalTo("GemFire Region must not be null"))); - new GemfireCache(null); + try { + new GemfireCache(null); + } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("GemFire Region must not be null"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void getNameReturnsRegionName() { + when(mockRegion.getName()).thenReturn("Example"); + assertThat(GemfireCache.wrap(mockRegion).getName()).isEqualTo("Example"); + verify(mockRegion, times(1)).getName(); } @Test public void clearCallsRegionClear() { + GemfireCache.wrap(mockRegion).clear(); + verify(mockRegion, times(1)).clear(); } @Test public void evictCallsRegionRemoveWithKey() { + GemfireCache.wrap(mockRegion).evict("key"); - verify(mockRegion, never()).destroy(anyObject()); + + verify(mockRegion, never()).destroy(any()); verify(mockRegion, times(1)).remove(eq("key")); } @Test public void getReturnsValueWrapperForKey() { + when(mockRegion.get(eq("key"))).thenReturn("test"); Cache.ValueWrapper value = GemfireCache.wrap(mockRegion).get("key"); @@ -118,13 +125,17 @@ public class GemfireCacheUnitTests { @Test public void getReturnsNullForKey() { + when(mockRegion.get(anyString())).thenReturn(null); + assertThat(GemfireCache.wrap(mockRegion).get("key")).isNull(); + verify(mockRegion, times(1)).get(eq("key")); } @Test public void getReturnsValueForKeyAsDesiredType() { + when(mockRegion.get(eq("key"))).thenReturn(1); Object value = GemfireCache.wrap(mockRegion).get("key", Integer.class); @@ -138,71 +149,99 @@ public class GemfireCacheUnitTests { @Test public void getReturnsNullForKeyAsDesiredType() { + when(mockRegion.get(eq("key"))).thenReturn(null); + assertThat(GemfireCache.wrap(mockRegion).get("key", Double.class)).isNull(); + verify(mockRegion, times(1)).get(eq("key")); } @Test public void getReturnsValueForKeyWithNullDesiredType() { + when(mockRegion.get(eq("key"))).thenReturn(true); + assertThat(GemfireCache.wrap(mockRegion).get("key", (Class) null)).isTrue(); + verify(mockRegion, times(1)).get(eq("key")); } - @Test + @Test(expected = IllegalStateException.class) public void getThrowsIllegalStateExceptionForKeyWhenValueIsNotAnInstanceOfDesiredType() { + when(mockRegion.get(eq("key"))).thenReturn(1); try { - exception.expect(IllegalStateException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage(String.format("Cached value [1] is not an instance of type [%s]", - Boolean.class.getName())); - GemfireCache.wrap(mockRegion).get("key", Boolean.class); } + catch (IllegalStateException expected) { + + assertThat(expected).hasMessage("Cached value [1] is not an instance of type [%s]", + Boolean.class.getName()); + + assertThat(expected).hasNoCause(); + + throw expected; + } finally { verify(mockRegion, times(1)).get(eq("key")); } } @Test + @SuppressWarnings("unchecked") public void getReturnsValueFromCacheForKeyWithValueLoader() { + when(mockRegion.get(eq("key"))).thenReturn("test"); + assertThat(GemfireCache.wrap(mockRegion).get("key", mockCallable)).isEqualTo("test"); + verify(mockRegion, times(1)).get(eq("key")); - verifyZeroInteractions(mockCallable); + verifyNoInteractions(mockCallable); } @Test + @SuppressWarnings("unchecked") public void getReturnsValueFromCacheForKeyAfterSynchronizationWithValueLoader() { + when(mockRegion.get(eq("key"))).thenReturn(null).thenReturn("test"); + assertThat(GemfireCache.wrap(mockRegion).get("key", mockCallable)).isEqualTo("test"); + verify(mockRegion, times(2)).get(eq("key")); - verifyZeroInteractions(mockCallable); + verifyNoInteractions(mockCallable); } @Test + @SuppressWarnings("unchecked") public void getReturnsValueFromValueLoaderForKeyWithValueLoader() throws Exception { + when(mockRegion.get(anyString())).thenReturn(null); when(mockCallable.call()).thenReturn("mockValue"); + assertThat(GemfireCache.wrap(mockRegion).get("key", mockCallable)).isEqualTo("mockValue"); + verify(mockRegion, times(2)).get(eq("key")); verify(mockCallable, times(1)).call(); } - @Test + @SuppressWarnings("unchecked") + @Test(expected = Cache.ValueRetrievalException.class) public void getThrowsValueRetrievalExceptionForKeyWithValueLoader() throws Exception { + when(mockRegion.get(anyString())).thenReturn(null); when(mockCallable.call()).thenThrow(new IllegalStateException("test")); try { - exception.expect(Cache.ValueRetrievalException.class); - exception.expectCause(isA(IllegalStateException.class)); - GemfireCache.wrap(mockRegion).get("key", mockCallable); } + catch (Cache.ValueRetrievalException expected) { + + assertThat(expected).hasCauseInstanceOf(IllegalStateException.class); + + throw expected; + } finally { verify(mockRegion, times(2)).get(eq("key")); verify(mockCallable, times(1)).call(); @@ -212,21 +251,26 @@ public class GemfireCacheUnitTests { @Test @SuppressWarnings("unchecked") public void putCachesValue() { + GemfireCache.wrap(mockRegion).put("key", "test"); + verify(mockRegion, times(1)).put(eq("key"), eq("test")); } @Test @SuppressWarnings("unchecked") public void putDoesNotCacheNull() { + GemfireCache.wrap(mockRegion).put("key", null); - verify(mockRegion, never()).put(anyString(), anyObject()); + + verify(mockRegion, never()).put(anyString(), any()); } @Test @SuppressWarnings("unchecked") public void putIfAbsentReturnsExistingValue() { - when(mockRegion.putIfAbsent(eq("key"), anyObject())).thenReturn("test"); + + when(mockRegion.putIfAbsent(eq("key"), any())).thenReturn("test"); Cache.ValueWrapper value = GemfireCache.wrap(mockRegion).putIfAbsent("key", "mockValue"); @@ -239,7 +283,8 @@ public class GemfireCacheUnitTests { @Test @SuppressWarnings("unchecked") public void putIfAbsentReturnsNull() { - when(mockRegion.putIfAbsent(eq("key"), anyObject())).thenReturn(null); + + when(mockRegion.putIfAbsent(eq("key"), any())).thenReturn(null); Cache.ValueWrapper value = GemfireCache.wrap(mockRegion).putIfAbsent("key", "mockValue"); diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/client/InterestResultPolicyConverterUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/client/InterestResultPolicyConverterUnitTests.java index 4cdd666a..354eafbc 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/client/InterestResultPolicyConverterUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/client/InterestResultPolicyConverterUnitTests.java @@ -13,35 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire.client; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.apache.geode.cache.InterestResultPolicy; /** - * Unit tests for {@link InterestResultPolicyConverter}. + * Unit Tests for {@link InterestResultPolicyConverter}. * * @author John Blum * @see org.junit.Test + * @see org.apache.geode.cache.InterestResultPolicy * @see org.springframework.data.gemfire.client.InterestResultPolicyConverter * @see org.springframework.data.gemfire.client.InterestResultPolicyType - * @see org.apache.geode.cache.InterestResultPolicy * @since 1.6.0 */ public class InterestResultPolicyConverterUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - private final InterestResultPolicyConverter converter = new InterestResultPolicyConverter(); @After @@ -51,38 +43,54 @@ public class InterestResultPolicyConverterUnitTests { @Test public void convert() { + assertThat(converter.convert("NONE")).isEqualTo(InterestResultPolicy.NONE); assertThat(converter.convert("kEyS_ValUes")).isEqualTo(InterestResultPolicy.KEYS_VALUES); assertThat(converter.convert("nONe")).isEqualTo(InterestResultPolicy.NONE); } - @Test + @Test(expected = IllegalArgumentException.class) public void convertIllegalValue() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[illegal_value] is not a valid InterestResultPolicy"); - converter.convert("illegal_value"); + try { + converter.convert("illegal_value"); + } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[illegal_value] is not a valid InterestResultPolicy"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void setAsText() { + assertThat(converter.getValue()).isNull(); + converter.setAsText("NOne"); + assertThat(converter.getValue()).isEqualTo(InterestResultPolicy.NONE); + converter.setAsText("KeYs"); + assertThat(converter.getValue()).isEqualTo(InterestResultPolicy.KEYS); } - @Test + @Test(expected = IllegalArgumentException.class) public void setAsTextWithIllegalValue() { - try { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[illegal_value] is not a valid InterestResultPolicy"); + try { converter.setAsText("illegal_value"); } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[illegal_value] is not a valid InterestResultPolicy"); + assertThat(expected).hasNoCause(); + + throw expected; + } finally { assertThat(converter.getValue()).isNull(); } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/client/InterestUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/client/InterestUnitTests.java index 8fd7d72d..899e1535 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/client/InterestUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/client/InterestUnitTests.java @@ -13,27 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire.client; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; import static org.springframework.data.gemfire.client.Interest.Type.KEY; import static org.springframework.data.gemfire.client.Interest.Type.REGEX; import static org.springframework.data.gemfire.client.Interest.newInterest; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.apache.geode.cache.InterestResultPolicy; /** - * Unit tests for {@link Interest}. + * Unit Tests for {@link Interest}. * * @author John Blum * @author Mark Paluch @@ -47,11 +42,9 @@ public class InterestUnitTests { protected static final boolean DURABLE = true; protected static final boolean DO_NOT_RECEIVE_VALUES = false; - @Rule - public ExpectedException exception = ExpectedException.none(); - @Test public void constructInterestWithKey() { + Interest interest = new Interest<>("testKey"); assertThat(interest.getKey()).isEqualTo("testKey"); @@ -69,6 +62,7 @@ public class InterestUnitTests { @Test public void constructInterestWithKeyAndPolicy() { + Interest interest = new Interest<>("mockKey", InterestResultPolicy.KEYS); assertThat(interest.getKey()).isEqualTo("mockKey"); @@ -86,6 +80,7 @@ public class InterestUnitTests { @Test public void constructInterestWithKeyPolicyAndDurability() { + Interest interest = new Interest<>(".*Key", InterestResultPolicy.NONE, DURABLE); assertThat(interest.getKey()).isEqualTo(".*Key"); @@ -103,6 +98,7 @@ public class InterestUnitTests { @Test public void constructInterestWithKeyPolicyDurabilityAndReceiveValues() { + List keys = asList("KeyOne", "KeyTwo", "KeyThree"); Interest interest = new Interest<>(keys, InterestResultPolicy.KEYS_VALUES, @@ -121,17 +117,24 @@ public class InterestUnitTests { assertThat(interest.toString()).isEqualTo(expectedString); } - @Test + @Test(expected = IllegalArgumentException.class) public void constructInterestWithNullKey() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("Key is required"); - new Interest<>(null); + try { + new Interest<>(null); + } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("Key is required"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void isAlphanumericWhitespace() { + Interest interest = newInterest("key"); assertThat(interest.isAlphaNumericWhitespace('a')).isTrue(); @@ -147,6 +150,7 @@ public class InterestUnitTests { @Test public void isNonAlphanumericWhitespace() { + Interest interest = newInterest("key"); assertThat(interest.isNotAlphaNumericWhitespace('@')).isTrue(); @@ -163,6 +167,7 @@ public class InterestUnitTests { @Test public void containsNonAlphanumericWhitespace() { + Interest interest = newInterest("key"); assertThat(interest.containsNonAlphaNumericWhitespace(".*")).isTrue(); @@ -175,6 +180,7 @@ public class InterestUnitTests { @Test public void containsOnlyAlphanumericWhitespace() { + Interest interest = newInterest("key"); assertThat(interest.containsNonAlphaNumericWhitespace("0")).isFalse(); @@ -190,6 +196,7 @@ public class InterestUnitTests { @Test public void isRegularExpression() { + Interest interest = newInterest("key"); assertThat(interest.isRegularExpression(".?")).isTrue(); @@ -209,6 +216,7 @@ public class InterestUnitTests { @Test public void isNotRegularExpression() { + Interest interest = newInterest("key"); assertThat(interest.isRegularExpression("abc")).isFalse(); @@ -222,6 +230,7 @@ public class InterestUnitTests { @Test public void resolveTypeIsCorrect() { + assertThat(newInterest(".*").resolveType(KEY)).isEqualTo(KEY); assertThat(newInterest("key").resolveType(REGEX)).isEqualTo(REGEX); assertThat(newInterest("key").resolveType(null)).isEqualTo(KEY); @@ -232,6 +241,7 @@ public class InterestUnitTests { @Test @SuppressWarnings("unchecked") public void setAndGetStateIsCorrect() { + Interest interest = newInterest("key"); assertThat(interest.isDurable()).isFalse(); @@ -255,6 +265,7 @@ public class InterestUnitTests { @Test public void setAndGetPolicy() { + Interest interest = newInterest("key"); assertThat(interest.getPolicy()).isEqualTo(InterestResultPolicy.DEFAULT); @@ -275,6 +286,7 @@ public class InterestUnitTests { @Test public void isKeyTypeIsCorrect() { + Interest interest = newInterest("key"); assertThat(interest.getType()).isEqualTo(KEY); @@ -293,6 +305,7 @@ public class InterestUnitTests { @Test public void isRegexTypeIsCorrect() { + Interest interest = newInterest("key"); assertThat(interest.getType()).isEqualTo(KEY); @@ -311,7 +324,10 @@ public class InterestUnitTests { @Test public void newInterestWithBuilder() { - Interest interest = newInterest(".*").makeDurable().receivesValues(false) + + Interest interest = newInterest(".*") + .makeDurable() + .receivesValues(false) .usingPolicy(InterestResultPolicy.KEYS); assertThat(interest).isNotNull(); @@ -325,7 +341,10 @@ public class InterestUnitTests { @Test @SuppressWarnings("unchecked") public void newInterestWithBuilderHonorsType() { - Interest interest = newInterest(".*").asType(KEY).withKey("^.+Key\\p{Digit}$") + + Interest interest = newInterest(".*") + .asType(KEY) + .withKey("^.+Key\\p{Digit}$") .usingPolicy(InterestResultPolicy.NONE); assertThat(interest).isNotNull(); diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/support/AutoRegionLookupBeanPostProcessorUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/support/AutoRegionLookupBeanPostProcessorUnitTests.java index 7d387146..1e38e2a6 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/support/AutoRegionLookupBeanPostProcessorUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/support/AutoRegionLookupBeanPostProcessorUnitTests.java @@ -14,22 +14,19 @@ * limitations under the License. * */ - package org.springframework.data.gemfire.config.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.any; -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.util.Collections; @@ -37,9 +34,7 @@ import java.util.HashSet; import java.util.Set; 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.junit.MockitoJUnitRunner; @@ -52,7 +47,7 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.data.gemfire.util.CollectionUtils; /** - * Unit tests for {@link AutoRegionLookupBeanPostProcessor}. + * Unit Tests for {@link AutoRegionLookupBeanPostProcessor}. * * @author John Blum * @see org.junit.Test @@ -65,9 +60,6 @@ import org.springframework.data.gemfire.util.CollectionUtils; @RunWith(MockitoJUnitRunner.class) public class AutoRegionLookupBeanPostProcessorUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - private AutoRegionLookupBeanPostProcessor autoRegionLookupBeanPostProcessor; @Mock @@ -101,39 +93,55 @@ public class AutoRegionLookupBeanPostProcessorUnitTests { assertThat(autoRegionLookupBeanPostProcessor.getBeanFactory()).isSameAs(mockBeanFactory); } - @Test + @Test(expected = IllegalArgumentException.class) public void setBeanFactoryToIncompatibleBeanFactoryType() { BeanFactory mockBeanFactory = mock(BeanFactory.class); - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage(String.format("BeanFactory [%1$s] must be an instance of %2$s", - mockBeanFactory.getClass().getName(), ConfigurableListableBeanFactory.class.getSimpleName())); + try { + autoRegionLookupBeanPostProcessor.setBeanFactory(mockBeanFactory); + } + catch (IllegalArgumentException expected) { - autoRegionLookupBeanPostProcessor.setBeanFactory(mockBeanFactory); + assertThat(expected).hasMessage("BeanFactory [%1$s] must be an instance of %2$s", + mockBeanFactory.getClass().getName(), ConfigurableListableBeanFactory.class.getSimpleName()); + + assertThat(expected).hasNoCause(); + + throw expected; + } } - @Test - @SuppressWarnings("all") + @Test(expected = IllegalArgumentException.class) public void setBeanFactoryToNull() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage(String.format("BeanFactory [null] must be an instance of %s", - ConfigurableListableBeanFactory.class.getSimpleName())); + try { + autoRegionLookupBeanPostProcessor.setBeanFactory(null); + } + catch (IllegalArgumentException expected) { - autoRegionLookupBeanPostProcessor.setBeanFactory(null); + assertThat(expected).hasMessage("BeanFactory [null] must be an instance of %s", + ConfigurableListableBeanFactory.class.getSimpleName()); + + assertThat(expected).hasNoCause(); + + throw expected; + } } - @Test + @Test(expected = IllegalStateException.class) public void getBeanFactoryUninitialized() { - exception.expect(IllegalStateException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("BeanFactory was not properly configured"); + try { + autoRegionLookupBeanPostProcessor.getBeanFactory(); + } + catch (IllegalStateException expected) { - autoRegionLookupBeanPostProcessor.getBeanFactory(); + assertThat(expected).hasMessage("BeanFactory was not properly configured"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test @@ -182,7 +190,7 @@ public class AutoRegionLookupBeanPostProcessorUnitTests { verify(mockGemFireCache, times(1)).rootRegions(); for (Region region : expected) { - verifyZeroInteractions(region); + verifyNoInteractions(region); } } @@ -236,13 +244,13 @@ public class AutoRegionLookupBeanPostProcessorUnitTests { autoRegionLookupBeanPostProcessor.setBeanFactory(mockBeanFactory); autoRegionLookupBeanPostProcessor.registerCacheRegionAsBean(null); - verifyZeroInteractions(mockBeanFactory); + verifyNoInteractions(mockBeanFactory); } @Test public void getBeanNameReturnsRegionFullPath() { - Region mockRegion = mockRegion("/Parent/Child"); + Region mockRegion = mockRegion("/Parent/Child"); assertThat(autoRegionLookupBeanPostProcessor.getBeanName(mockRegion)).isEqualTo("/Parent/Child"); @@ -253,7 +261,7 @@ public class AutoRegionLookupBeanPostProcessorUnitTests { @Test public void getBeanNameReturnsRegionName() { - Region mockRegion = mockRegion("/Example"); + Region mockRegion = mockRegion("/Example"); assertThat(autoRegionLookupBeanPostProcessor.getBeanName(mockRegion)).isEqualTo("Example"); @@ -267,7 +275,7 @@ public class AutoRegionLookupBeanPostProcessorUnitTests { Set> mockSubRegions = CollectionUtils.asSet(mockRegion("one"), mockRegion("two")); - Region mockRegion = mockRegion("parent"); + Region mockRegion = mockRegion("parent"); when(mockRegion.subregions(anyBoolean())).thenReturn(mockSubRegions); @@ -279,7 +287,7 @@ public class AutoRegionLookupBeanPostProcessorUnitTests { @Test public void nullSafeSubRegionsWhenSubRegionsIsNull() { - Region mockRegion = mockRegion("parent"); + Region mockRegion = mockRegion("parent"); when(mockRegion.subregions(anyBoolean())).thenReturn(null); diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/dao/GemfireDaoSupportUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/dao/GemfireDaoSupportUnitTests.java index f37fcbef..35616b4d 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/dao/GemfireDaoSupportUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/dao/GemfireDaoSupportUnitTests.java @@ -17,12 +17,8 @@ package org.springframework.data.gemfire.dao; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -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.junit.MockitoJUnitRunner; @@ -46,9 +42,6 @@ import org.springframework.data.gemfire.GemfireTemplate; @RunWith(MockitoJUnitRunner.class) public class GemfireDaoSupportUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - @Mock public Region mockRegion; @@ -82,9 +75,10 @@ public class GemfireDaoSupportUnitTests { } @Test - @SuppressWarnings("rawtypes") - public void createProperlyInitializedGemfireDaoSupportWithTemplate() throws Exception { + public void createProperlyInitializedGemfireDaoSupportWithTemplate() { + GemfireTemplate expectedGemfireTemplate = new GemfireTemplate(); + GemfireDaoSupport dao = new TestGemfireDaoSupport(); dao.setGemfireTemplate(expectedGemfireTemplate); @@ -94,15 +88,21 @@ public class GemfireDaoSupportUnitTests { assertThat(dao.getGemfireTemplate()).isEqualTo(expectedGemfireTemplate); } - @Test - public void invalidGemfireDaoSupportInstanceThrowsIllegalStateException() throws Exception { - exception.expect(IllegalStateException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("A GemFire Cache Region or instance of GemfireTemplate is required"); + @Test(expected = IllegalStateException.class) + public void invalidGemfireDaoSupportInstanceThrowsIllegalStateException() { - new TestGemfireDaoSupport().afterPropertiesSet(); + try { + new TestGemfireDaoSupport().afterPropertiesSet(); + } + catch (IllegalStateException expected) { + + assertThat(expected).hasMessage("A GemFire Cache Region or instance of GemfireTemplate is required"); + assertThat(expected).hasNoCause(); + + throw expected; + } } - private static final class TestGemfireDaoSupport extends GemfireDaoSupport { - } + private static final class TestGemfireDaoSupport extends GemfireDaoSupport { } + } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/eviction/EvictionActionConverterUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/eviction/EvictionActionConverterUnitTests.java index 773bd7e6..eebd8c3d 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/eviction/EvictionActionConverterUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/eviction/EvictionActionConverterUnitTests.java @@ -14,35 +14,27 @@ * limitations under the License. * */ - package org.springframework.data.gemfire.eviction; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; + +import org.junit.After; +import org.junit.Test; import org.apache.geode.cache.EvictionAction; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - /** - * Unit tests for {@link EvictionActionConverter}. + * Unit Tests for {@link EvictionActionConverter}. * * @author John Blum * @see org.junit.Test - * @see EvictionActionConverter * @see org.apache.geode.cache.EvictionAction + * @see org.springframework.data.gemfire.eviction.EvictionActionConverter * @since 1.6.0 */ public class EvictionActionConverterUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - - private EvictionActionConverter converter = new EvictionActionConverter(); + private final EvictionActionConverter converter = new EvictionActionConverter(); @After public void tearDown() { @@ -51,38 +43,54 @@ public class EvictionActionConverterUnitTests { @Test public void convert() { + assertThat(converter.convert("local_destroy")).isEqualTo(EvictionAction.LOCAL_DESTROY); assertThat(converter.convert("None")).isEqualTo(EvictionAction.NONE); assertThat(converter.convert("OverFlow_TO_dIsk")).isEqualTo(EvictionAction.OVERFLOW_TO_DISK); } - @Test + @Test(expected = IllegalArgumentException.class) public void convertIllegalValue() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[invalid_value] is not a valid EvictionAction"); - converter.convert("invalid_value"); + try { + converter.convert("invalid_value"); + } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[invalid_value] is not a valid EvictionAction"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void setAsText() { + assertThat(converter.getValue()).isNull(); + converter.setAsText("Local_Destroy"); + assertThat(converter.getValue()).isEqualTo(EvictionAction.LOCAL_DESTROY); + converter.setAsText("overflow_to_disk"); + assertThat(converter.getValue()).isEqualTo(EvictionAction.OVERFLOW_TO_DISK); } - @Test + @Test(expected = IllegalArgumentException.class) public void setAsTextWithIllegalValue() { - try { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[destroy] is not a valid EvictionAction"); + try { converter.setAsText("destroy"); } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[destroy] is not a valid EvictionAction"); + assertThat(expected).hasNoCause(); + + throw expected; + } finally { assertThat(converter.getValue()).isNull(); } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/eviction/EvictionPolicyConverterUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/eviction/EvictionPolicyConverterUnitTests.java index 55baa32a..1b81c514 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/eviction/EvictionPolicyConverterUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/eviction/EvictionPolicyConverterUnitTests.java @@ -14,32 +14,25 @@ * limitations under the License. * */ - package org.springframework.data.gemfire.eviction; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** - * Unit tests for {@link EvictionPolicyConverter}. + * Unit Tests for {@link EvictionPolicyConverter}. * * @author John Blum * @see org.junit.Test - * @see EvictionPolicyConverter - * @see EvictionPolicyType + * @see org.apache.geode.cache.EvictionAttributes + * @see org.springframework.data.gemfire.eviction.EvictionPolicyConverter + * @see org.springframework.data.gemfire.eviction.EvictionPolicyType * @since 1.6.0 */ public class EvictionPolicyConverterUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - private final EvictionPolicyConverter converter = new EvictionPolicyConverter(); @After @@ -49,39 +42,55 @@ public class EvictionPolicyConverterUnitTests { @Test public void convert() { + assertThat(converter.convert("entry_count")).isEqualTo(EvictionPolicyType.ENTRY_COUNT); assertThat(converter.convert("Heap_Percentage")).isEqualTo(EvictionPolicyType.HEAP_PERCENTAGE); assertThat(converter.convert("MEMorY_SiZe")).isEqualTo(EvictionPolicyType.MEMORY_SIZE); assertThat(converter.convert("NONE")).isEqualTo(EvictionPolicyType.NONE); } - @Test + @Test(expected = IllegalArgumentException.class) public void convertIllegalValue() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[LIFO_MEMORY] is not a valid EvictionPolicyType"); - converter.convert("LIFO_MEMORY"); + try { + converter.convert("LIFO_MEMORY"); + } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[LIFO_MEMORY] is not a valid EvictionPolicyType"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void setAsText() { + assertThat(converter.getValue()).isNull(); + converter.setAsText("heap_percentage"); + assertThat(converter.getValue()).isEqualTo(EvictionPolicyType.HEAP_PERCENTAGE); + converter.setAsText("NOne"); + assertThat(converter.getValue()).isEqualTo(EvictionPolicyType.NONE); } - @Test + @Test(expected = IllegalArgumentException.class) public void setAsTextWithIllegalValue() { - try { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[LRU_COUNT] is not a valid EvictionPolicyType"); + try { converter.setAsText("LRU_COUNT"); } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[LRU_COUNT] is not a valid EvictionPolicyType"); + assertThat(expected).hasNoCause(); + + throw expected; + } finally { assertThat(converter.getValue()).isNull(); } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/expiration/ExpirationActionConverterUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/expiration/ExpirationActionConverterUnitTests.java index 6b077674..9d65b80b 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/expiration/ExpirationActionConverterUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/expiration/ExpirationActionConverterUnitTests.java @@ -14,33 +14,26 @@ * limitations under the License. * */ - package org.springframework.data.gemfire.expiration; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; + +import org.junit.After; +import org.junit.Test; import org.apache.geode.cache.ExpirationAction; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - /** - * Unit tests for {@link ExpirationActionConverter}. + * Unit Tests for {@link ExpirationActionConverter}. * * @author John Blum * @see org.junit.Test - * @see ExpirationActionConverter + * @see org.apache.geode.cache.EvictionAction + * @see org.springframework.data.gemfire.expiration.ExpirationActionConverter * @since 1.6.0 */ public class ExpirationActionConverterUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - private final ExpirationActionConverter converter = new ExpirationActionConverter(); @After @@ -56,33 +49,48 @@ public class ExpirationActionConverterUnitTests { assertThat(converter.convert("Local_Invalidate")).isEqualTo(ExpirationAction.LOCAL_INVALIDATE); } - @Test + @Test(expected = IllegalArgumentException.class) public void convertIllegalValue() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[illegal_value] is not a valid ExpirationAction"); - converter.convert("illegal_value"); + try { + converter.convert("illegal_value"); + } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[illegal_value] is not a valid ExpirationAction"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void setAsText() { + assertThat(converter.getValue()).isNull(); + converter.setAsText("InValidAte"); + assertThat(converter.getValue()).isEqualTo(ExpirationAction.INVALIDATE); + converter.setAsText("Local_Destroy"); + assertThat(converter.getValue()).isEqualTo(ExpirationAction.LOCAL_DESTROY); } - @Test + @Test(expected = IllegalArgumentException.class) public void setAsTextWithIllegalValue() { - try { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[destruction] is not a valid ExpirationAction"); + try { converter.setAsText("destruction"); } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[destruction] is not a valid ExpirationAction"); + assertThat(expected).hasNoCause(); + + throw expected; + } finally { assertThat(converter.getValue()).isNull(); } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/mapping/GemfirePersistentEntityUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/mapping/GemfirePersistentEntityUnitTests.java index a6e50ca0..c5443d28 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/mapping/GemfirePersistentEntityUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/mapping/GemfirePersistentEntityUnitTests.java @@ -13,19 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire.mapping; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; import java.math.BigDecimal; import java.math.BigInteger; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.data.annotation.Id; import org.springframework.data.gemfire.mapping.annotation.Region; @@ -34,21 +29,17 @@ import org.springframework.data.mapping.MappingException; import org.springframework.data.util.ClassTypeInformation; /** - * Unit tests for {@link GemfirePersistentEntity}. + * Unit Tests for {@link GemfirePersistentEntity}. * * @author Oliver Gierke * @author John Blum * @author Gregory Green - * @see org.junit.Rule * @see org.junit.Test * @see org.springframework.data.gemfire.mapping.GemfirePersistentEntity */ public class GemfirePersistentEntityUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - - private GemfireMappingContext mappingContext = new GemfireMappingContext(); + private final GemfireMappingContext mappingContext = new GemfireMappingContext(); protected IdentifierAccessor getIdentifierAccessor(Object domainObject) { return getMappingContextPersistentEntity(domainObject).getIdentifierAccessor(domainObject); @@ -56,7 +47,7 @@ public class GemfirePersistentEntityUnitTests { @SuppressWarnings("unchecked") protected GemfirePersistentEntity getMappingContextPersistentEntity(Object domainObject) { - return this.getMappingContextPersistentEntity((Class) domainObject.getClass()); + return this.getMappingContextPersistentEntity((Class) domainObject.getClass()); } @SuppressWarnings("unchecked") @@ -86,8 +77,8 @@ public class GemfirePersistentEntityUnitTests { } @Test - @SuppressWarnings("unchecked") public void bigDecimalPersistentPropertyIsNotAnEntity() { + GemfirePersistentEntity entity = getMappingContextPersistentEntity(ExampleDomainObject.class); @@ -101,7 +92,6 @@ public class GemfirePersistentEntityUnitTests { } @Test - @SuppressWarnings("unchecked") public void bigIntegerPersistentPropertyIsNotAnEntity() { GemfirePersistentEntity entity = @@ -163,21 +153,25 @@ public class GemfirePersistentEntityUnitTests { AmbiguousIdAnnotatedFieldAndIdAnnotatedPropertyEntity entity = new AmbiguousIdAnnotatedFieldAndIdAnnotatedPropertyEntity(); - String expectedMessage = String.format("Attempt to add explicit id property [ssn] but already have id property [id] registered as explicit;" - + " Please check your object [%s] mapping configuration", entity.getClass().getName()); + try { + getIdentifierAccessor(new AmbiguousIdAnnotatedFieldAndIdAnnotatedPropertyEntity()); + } + catch (MappingException expected) { - exception.expect(MappingException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage(expectedMessage); + assertThat(expected).hasMessage("Attempt to add explicit id property [ssn] but already have id property [id] registered as explicit;" + + " Please check your object [%s] mapping configuration", entity.getClass().getName()); - getIdentifierAccessor(new AmbiguousIdAnnotatedFieldAndIdAnnotatedPropertyEntity()); + assertThat(expected).hasNoCause(); + + throw expected; + } } @SuppressWarnings("unused") static class AmbiguousIdAnnotatedFieldAndIdAnnotatedPropertyEntity { @Id - private Long id = 1L; + private final Long id = 1L; @Id public String getSsn() { @@ -188,7 +182,7 @@ public class GemfirePersistentEntityUnitTests { static class IdAnnotatedFieldAndPropertyEntity { @Id - private Long id = 1L; + private final Long id = 1L; @Id public Long getId() { @@ -196,8 +190,9 @@ public class GemfirePersistentEntityUnitTests { } } + @SuppressWarnings("unused") static class NonIdAnnotatedIdFieldEntity { - private Long id = 123L; + private final Long id = 123L; } static class NonIdAnnotatedIdGetterEntity { @@ -206,16 +201,13 @@ public class GemfirePersistentEntityUnitTests { } } - static class NonRegionAnnotatedEntity { - } + static class NonRegionAnnotatedEntity { } @Region("Foo") - static class NamedRegionAnnotatedEntity { - } + static class NamedRegionAnnotatedEntity { } @Region - static class UnnamedRegionAnnotatedEntity { - } + static class UnnamedRegionAnnotatedEntity { } @Region("Example") @SuppressWarnings("unused") diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/mapping/RegionsTest.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/mapping/RegionsUnitTests.java similarity index 75% rename from spring-data-geode/src/test/java/org/springframework/data/gemfire/mapping/RegionsTest.java rename to spring-data-geode/src/test/java/org/springframework/data/gemfire/mapping/RegionsUnitTests.java index eb966049..97b58008 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/mapping/RegionsTest.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/mapping/RegionsUnitTests.java @@ -13,14 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire.mapping; 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.any; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -28,27 +25,23 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.apache.geode.cache.Region; - 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.junit.MockitoJUnitRunner; +import org.apache.geode.cache.Region; + import org.springframework.data.gemfire.repository.sample.User; import org.springframework.data.mapping.context.MappingContext; /** - * The RegionsTest class is a test suite of test cases testing the contract and functionality of the Regions class. + * Unit Tests for {@link Regions}. * * @author John J. Blum - * @see org.junit.Rule * @see org.junit.Test - * @see org.junit.runner.RunWith * @see org.mockito.Mockito * @see org.mockito.junit.MockitoJUnitRunner * @see org.springframework.data.gemfire.mapping.Regions @@ -56,26 +49,25 @@ import org.springframework.data.mapping.context.MappingContext; */ @SuppressWarnings("unchecked") @RunWith(MockitoJUnitRunner.class) -public class RegionsTest { - - @Rule - public ExpectedException exception = ExpectedException.none(); +public class RegionsUnitTests { @Mock + @SuppressWarnings("rawtypes") private MappingContext mockMappingContext; - private Region mockUsers; - private Region mockAdminUsers; - private Region mockGuestUsers; + private Region mockUsers; + private Region mockAdminUsers; + private Region mockGuestUsers; private Regions regions; - protected Region mockRegion(String fullPath) { + private Region mockRegion(String fullPath) { return mockRegion(fullPath.substring(fullPath.lastIndexOf(Region.SEPARATOR) + 1), fullPath); } - protected Region mockRegion(String name, String fullPath) { - Region mockRegion = mock(Region.class, name); + private Region mockRegion(String name, String fullPath) { + + Region mockRegion = mock(Region.class, name); when(mockRegion.getName()).thenReturn(name); when(mockRegion.getFullPath()).thenReturn(fullPath); @@ -85,6 +77,7 @@ public class RegionsTest { @Before public void setup() { + mockUsers = mockRegion("/Users"); mockAdminUsers = mockRegion("/Users/Admin"); mockGuestUsers = mockRegion("/Users/Guest"); @@ -96,6 +89,7 @@ public class RegionsTest { @After public void tearDown() { + mockUsers = mockAdminUsers = mockGuestUsers = null; regions = null; } @@ -127,18 +121,24 @@ public class RegionsTest { assertThat(regions.getRegion(Object.class)).isNull(); } - @Test + @Test(expected = IllegalArgumentException.class) public void getRegionWithNullEntityTypeThrowsIllegalArgumentException() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("Entity type must not be null"); + try { + regions.getRegion((Class) null); + } + catch (IllegalArgumentException expected) { - regions.getRegion((Class) null); + assertThat(expected).hasMessage("Entity type must not be null"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void getRegionWithNameReturnsRegion() { + assertThat(regions.getRegion("Users")).isSameAs(mockUsers); assertThat(regions.getRegion("Admin")).isSameAs(mockAdminUsers); assertThat(regions.getRegion("Guest")).isSameAs(mockGuestUsers); @@ -146,6 +146,7 @@ public class RegionsTest { @Test public void getRegionWithPathReturnsRegion() { + assertThat(regions.getRegion("/Users")).isSameAs(mockUsers); assertThat(regions.getRegion("/Users/Admin")).isSameAs(mockAdminUsers); assertThat(regions.getRegion("/Users/Guest")).isSameAs(mockGuestUsers); @@ -161,31 +162,36 @@ public class RegionsTest { assertThat(regions.getRegion("/Non/Existing/Region/Path")).isNull(); } - @Test + @Test(expected = IllegalArgumentException.class) public void getRegionWithNullNameNullPathThrowsIllegalArgumentException() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("Region name/path is required"); + try { + regions.getRegion((String) null); + } + catch (IllegalArgumentException expected) { - regions.getRegion((String) null); + assertThat(expected).hasMessage("Region name/path is required"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void iterateRegions() { - List actualRegions = new ArrayList<>(3); + List> actualRegions = new ArrayList<>(3); - for (Region region : regions) { + for (Region region : regions) { actualRegions.add(region); } - List expectedRegions = Arrays.asList(mockUsers, mockAdminUsers, mockGuestUsers); + List> expectedRegions = Arrays.asList(mockUsers, mockAdminUsers, mockGuestUsers); assertThat(actualRegions).hasSize(expectedRegions.size() * 2); assertThat(actualRegions).containsAll(expectedRegions); } - interface Users { - } + interface Users { } + } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/cdi/CdiExtensionIntegrationTest.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/cdi/CdiExtensionIntegrationTest.java index b4b82d51..f459630f 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/cdi/CdiExtensionIntegrationTest.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/cdi/CdiExtensionIntegrationTest.java @@ -14,30 +14,24 @@ * limitations under the License. * */ - package org.springframework.data.gemfire.repository.cdi; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import javax.enterprise.inject.se.SeContainer; import javax.enterprise.inject.se.SeContainerInitializer; -import org.apache.geode.cache.CacheClosedException; -import org.apache.geode.cache.CacheFactory; - import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; +import org.apache.geode.cache.CacheClosedException; +import org.apache.geode.cache.CacheFactory; + import org.springframework.data.gemfire.repository.sample.Person; /** - * The CdiExtensionIntegrationTest class... + * Integration Tests for CDI. * * @author John Blum * @author Mark Paluch @@ -68,13 +62,15 @@ public class CdiExtensionIntegrationTest { private static void closeGemfireCache() { try { CacheFactory.getAnyInstance().close(); - } catch (CacheClosedException ignore) {} + } + catch (CacheClosedException ignore) {} } protected void assertIsExpectedPerson(Person actual, Person expected) { - assertThat(actual.getId(), is(equalTo(expected.getId()))); - assertThat(actual.getFirstname(), is(equalTo(expected.getFirstname()))); - assertThat(actual.getLastname(), is(equalTo(expected.getLastname()))); + + assertThat(actual.getId()).isEqualTo(expected.getId()); + assertThat(actual.getFirstname()).isEqualTo(expected.getFirstname()); + assertThat(actual.getLastname()).isEqualTo(expected.getLastname()); } @Test // DATAGEODE-42 @@ -82,13 +78,13 @@ public class CdiExtensionIntegrationTest { RepositoryClient repositoryClient = container.select(RepositoryClient.class).get(); - assertThat(repositoryClient.getPersonRepository(), is(notNullValue())); + assertThat(repositoryClient.getPersonRepository()).isNotNull(); Person expectedJonDoe = repositoryClient.newPerson("Jon", "Doe"); - assertThat(expectedJonDoe, is(notNullValue())); - assertThat(expectedJonDoe.getId(), is(greaterThan(0L))); - assertThat(expectedJonDoe.getName(), is(equalTo("Jon Doe"))); + assertThat(expectedJonDoe).isNotNull(); + assertThat(expectedJonDoe.getId()).isGreaterThan(0L); + assertThat(expectedJonDoe.getName()).isEqualTo("Jon Doe"); Person savedJonDoe = repositoryClient.save(expectedJonDoe); @@ -98,8 +94,8 @@ public class CdiExtensionIntegrationTest { assertIsExpectedPerson(foundJonDoe, expectedJonDoe); - assertThat(repositoryClient.delete(foundJonDoe), is(true)); - assertThat(repositoryClient.find(foundJonDoe.getId()), is(nullValue())); + assertThat(repositoryClient.delete(foundJonDoe)).isTrue(); + assertThat(repositoryClient.find(foundJonDoe.getId())).isNull(); } @Test // DATAGEODE-42 @@ -107,7 +103,6 @@ public class CdiExtensionIntegrationTest { RepositoryClient repositoryClient = container.select(RepositoryClient.class).get(); - assertThat(repositoryClient.getPersonRepository().returnOne(), is(equalTo(1))); + assertThat(repositoryClient.getPersonRepository().returnOne()).isEqualTo(1); } - } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/cdi/GemfireRepositoryBeanTest.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/cdi/GemfireRepositoryBeanTest.java index 68d4b524..d591d213 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/cdi/GemfireRepositoryBeanTest.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/cdi/GemfireRepositoryBeanTest.java @@ -14,23 +14,15 @@ * limitations under the License. * */ - package org.springframework.data.gemfire.repository.cdi; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.isIn; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; 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.util.ArrayUtils.asArray; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; @@ -46,16 +38,14 @@ import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; -import org.apache.geode.cache.Region; -import org.apache.geode.cache.RegionAttributes; - -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.junit.MockitoJUnitRunner; +import org.apache.geode.cache.Region; +import org.apache.geode.cache.RegionAttributes; + import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.data.gemfire.GemfireAccessor; @@ -68,14 +58,10 @@ import org.springframework.data.gemfire.util.CollectionUtils; import org.springframework.data.repository.config.CustomRepositoryImplementationDetector; /** - * The GemfireRepositoryBeanTest class is a test suite of test cases testing the contract and functionality - * of the GemfireRepositoryBean class. + * Unit Tests for {@link GemfireRepositoryBean}. * * @author John Blum - * @see org.junit.Rule * @see org.junit.Test - * @see org.junit.rules.ExpectedException - * @see org.junit.runner.RunWith * @see org.mockito.Mock * @see org.mockito.Mockito * @see org.mockito.junit.MockitoJUnitRunner @@ -83,12 +69,9 @@ import org.springframework.data.repository.config.CustomRepositoryImplementation * @since 1.0.0 */ @RunWith(MockitoJUnitRunner.class) -@SuppressWarnings("unchecked") +@SuppressWarnings({ "rawtypes", "unchecked" }) public class GemfireRepositoryBeanTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Mock private BeanManager mockBeanManager; @@ -117,7 +100,7 @@ public class GemfireRepositoryBeanTest { new GemfireRepositoryBean<>(this.mockBeanManager, PersonRepository.class, Collections.emptySet(), newCustomRepositoryImplementationDetector(), null, null); - assertThat(repositoryBean.getDependencyInstance(mockRegionBean, Region.class), is(equalTo(mockRegion))); + assertThat(repositoryBean.getDependencyInstance(mockRegionBean, Region.class)).isEqualTo(mockRegion); verify(mockBeanManager, times(1)).createCreationalContext(eq(mockRegionBean)); verify(mockBeanManager, times(1)) @@ -131,8 +114,8 @@ public class GemfireRepositoryBeanTest { new GemfireRepositoryBean<>(this.mockBeanManager, PersonRepository.class, Collections.emptySet(), newCustomRepositoryImplementationDetector(), null, null); - assertThat(repositoryBean.resolveGemfireMappingContext(), - is(equalTo(GemfireRepositoryBean.DEFAULT_GEMFIRE_MAPPING_CONTEXT))); + assertThat(repositoryBean.resolveGemfireMappingContext()) + .isEqualTo(GemfireRepositoryBean.DEFAULT_GEMFIRE_MAPPING_CONTEXT); } @Test @@ -154,7 +137,7 @@ public class GemfireRepositoryBeanTest { GemfireMappingContext actualGemfireMappingContext = repositoryBean.resolveGemfireMappingContext(); - assertThat(actualGemfireMappingContext, is(equalTo(expectedGemfireMappingContext))); + assertThat(actualGemfireMappingContext).isEqualTo(expectedGemfireMappingContext); verify(mockBeanManager, times(1)).createCreationalContext(eq(mockMappingContextBean)); verify(mockBeanManager, times(1)).getReference(eq(mockMappingContextBean), eq(GemfireMappingContext.class), @@ -172,8 +155,8 @@ public class GemfireRepositoryBeanTest { Bean mockRegionBeanOne = mock(Bean.class); Bean mockRegionBeanTwo = mock(Bean.class); - when(mockRegionBeanOne.getTypes()).thenReturn(CollectionUtils.asSet((Type) Region.class)); - when(mockRegionBeanTwo.getTypes()).thenReturn(CollectionUtils.asSet((Type) Region.class)); + when(mockRegionBeanOne.getTypes()).thenReturn(CollectionUtils.asSet(Region.class)); + when(mockRegionBeanTwo.getTypes()).thenReturn(CollectionUtils.asSet(Region.class)); when(mockBeanManager.createCreationalContext(any(Bean.class))).thenReturn(mockCreationalContext); when(mockBeanManager.getReference(eq(mockRegionBeanOne), eq(Region.class), eq(mockCreationalContext))) .thenReturn(mockRegionOne); @@ -186,8 +169,8 @@ public class GemfireRepositoryBeanTest { Iterable regions = repositoryBean.resolveGemfireRegions(); - assertThat(regions, is(notNullValue())); - assertThat(toSet(regions).containsAll(CollectionUtils.asSet(mockRegionOne, mockRegionTwo)), is(true)); + assertThat(regions).isNotNull(); + assertThat(toSet(regions).containsAll(CollectionUtils.asSet(mockRegionOne, mockRegionTwo))).isTrue(); verify(mockRegionBeanOne, times(1)).getTypes(); verify(mockRegionBeanTwo, times(1)).getTypes(); @@ -211,9 +194,8 @@ public class GemfireRepositoryBeanTest { new GemfireRepositoryBean<>(this.mockBeanManager, PersonRepository.class, Collections.emptySet(), newCustomRepositoryImplementationDetector(), null, null); - assertThat(repositoryBean.resolveType(mockBean, Region.class), is(equalTo(Region.class))); - assertThat(repositoryBean.resolveType(mockBean, Map.class), isIn(asArray((Type) Map.class, - ConcurrentMap.class, Region.class))); + assertThat(repositoryBean.resolveType(mockBean, Region.class)).isEqualTo(Region.class); + assertThat(repositoryBean.resolveType(mockBean, Map.class)).isIn(Map.class, ConcurrentMap.class, Region.class); verify(mockBean, times(2)).getTypes(); } @@ -227,24 +209,24 @@ public class GemfireRepositoryBeanTest { ParameterizedType mockParameterizedType = mock(ParameterizedType.class); - assertThat(parameterizedTypeMap.getClass(), is(instanceOf(Type.class))); - assertThat(parameterizedTypeMap.getClass().getGenericSuperclass(), is(instanceOf(ParameterizedType.class))); - assertThat(parameterizedTypeMap.getClass().getTypeParameters().length, is(equalTo(2))); + assertThat(parameterizedTypeMap.getClass()).isInstanceOf(Type.class); + assertThat(parameterizedTypeMap.getClass().getGenericSuperclass()).isInstanceOf(ParameterizedType.class); + assertThat(parameterizedTypeMap.getClass().getTypeParameters().length).isEqualTo(2); - when(mockBean.getTypes()).thenReturn(CollectionUtils.asSet((Type) mockParameterizedType)); + when(mockBean.getTypes()).thenReturn(CollectionUtils.asSet(mockParameterizedType)); when(mockParameterizedType.getRawType()).thenReturn(parameterizedTypeMap.getClass()); GemfireRepositoryBean repositoryBean = new GemfireRepositoryBean<>(this.mockBeanManager, PersonRepository.class, Collections.emptySet(), newCustomRepositoryImplementationDetector(), null, null); - assertThat(repositoryBean.resolveType(mockBean, Map.class), is(equalTo(mockParameterizedType))); + assertThat(repositoryBean.resolveType(mockBean, Map.class)).isEqualTo(mockParameterizedType); verify(mockBean, times(1)).getTypes(); verify(mockParameterizedType, times(1)).getRawType(); } - @Test + @Test(expected = IllegalStateException.class) public void resolveTypeWithUnresolvableType() { Bean mockBean = mock(Bean.class); @@ -256,14 +238,18 @@ public class GemfireRepositoryBeanTest { newCustomRepositoryImplementationDetector(), null, null); try { - expectedException.expect(IllegalStateException.class); - expectedException.expectCause(is(nullValue(Throwable.class))); - expectedException.expectMessage(is(equalTo(String.format( - "unable to resolve bean instance of type [%1$s] from bean definition [%2$s]", - Region.class, mockBean)))); - repositoryBean.resolveType(mockBean, Region.class); } + catch (IllegalStateException expected) { + + assertThat(expected) + .hasMessage("unable to resolve bean instance of type [%1$s] from bean definition [%2$s]", + Region.class, mockBean); + + assertThat(expected).hasNoCause(); + + throw expected; + } finally { verify(mockBean, times(1)).getTypes(); } @@ -271,7 +257,7 @@ public class GemfireRepositoryBeanTest { @Test // IntegrationTest - public void createGemfireRepositoryInstanceSuccessfully() throws Exception { + public void createGemfireRepositoryInstanceSuccessfully() { Bean mockRegionBean = mock(Bean.class); @@ -284,7 +270,7 @@ public class GemfireRepositoryBeanTest { when(mockRegion.getName()).thenReturn("Person"); when(mockRegion.getAttributes()).thenReturn(mockRegionAttributes); when(mockRegionAttributes.getKeyConstraint()).thenReturn(Long.class); - when(mockRegionBean.getTypes()).thenReturn(CollectionUtils.asSet((Type) Region.class)); + when(mockRegionBean.getTypes()).thenReturn(CollectionUtils.asSet(Region.class)); when(mockBeanManager.createCreationalContext(any(Bean.class))).thenReturn(mockCreationalContext); when(mockBeanManager.getReference(eq(mockRegionBean), eq(Region.class), eq(mockCreationalContext))) .thenReturn(mockRegion); @@ -304,20 +290,19 @@ public class GemfireRepositoryBeanTest { gemfireRepositoryFactory.addRepositoryProxyPostProcessor((factory, repositoryInformation) -> { try { - assertThat(repositoryInformation.getRepositoryInterface(), - is(equalTo(PersonRepository.class))); - assertThat(repositoryInformation.getRepositoryBaseClass(), - is(equalTo(SimpleGemfireRepository.class))); - assertThat(repositoryInformation.getDomainType(), is(equalTo(Person.class))); - assertThat(repositoryInformation.getIdType(), is(equalTo(Long.class))); - assertThat(factory.getTargetClass(), is(equalTo(SimpleGemfireRepository.class))); + assertThat(repositoryInformation.getRepositoryInterface()).isEqualTo(PersonRepository.class); + assertThat(repositoryInformation.getRepositoryBaseClass()) + .isEqualTo(SimpleGemfireRepository.class); + assertThat(repositoryInformation.getDomainType()).isEqualTo(Person.class); + assertThat(repositoryInformation.getIdType()).isEqualTo(Long.class); + assertThat(factory.getTargetClass()).isEqualTo(SimpleGemfireRepository.class); Object gemfireRepository = factory.getTargetSource().getTarget(); GemfireAccessor gemfireAccessor = TestUtils.readField("template", gemfireRepository); - assertThat(gemfireAccessor, is(notNullValue())); - assertThat(gemfireAccessor.getRegion(), is(equalTo(mockRegion))); + assertThat(gemfireAccessor).isNotNull(); + assertThat(gemfireAccessor.getRegion()).isEqualTo(mockRegion); repositoryProxyPostProcessed.set(true); } @@ -333,8 +318,8 @@ public class GemfireRepositoryBeanTest { GemfireRepository gemfireRepository = repositoryBean.create(null, PersonRepository.class); - assertThat(gemfireRepository, is(notNullValue())); - assertThat(repositoryProxyPostProcessed.get(), is(true)); + assertThat(gemfireRepository).isNotNull(); + assertThat(repositoryProxyPostProcessed.get()).isTrue(); verify(mockBeanManager, times(1)).createCreationalContext(eq(mockRegionBean)); verify(mockBeanManager, times(1)).getReference(eq(mockRegionBean), eq(Region.class), @@ -345,13 +330,16 @@ public class GemfireRepositoryBeanTest { verify(mockRegionAttributes, times(1)).getKeyConstraint(); } - class TestMap extends AbstractMap { - @Override public Set> entrySet() { + @SuppressWarnings("unused") + static class TestMap extends AbstractMap { + + @Override + public Set> entrySet() { return Collections.emptySet(); } } - class Person {} + static class Person {} interface PersonRepository extends GemfireRepository { } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/cdi/GemfireRepositoryExtensionTest.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/cdi/GemfireRepositoryExtensionTest.java index cf1f09e5..d1ac89dc 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/cdi/GemfireRepositoryExtensionTest.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/cdi/GemfireRepositoryExtensionTest.java @@ -14,14 +14,10 @@ * limitations under the License. * */ - package org.springframework.data.gemfire.repository.cdi; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.isA; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -29,7 +25,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.lang.annotation.Annotation; -import java.lang.reflect.Type; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; @@ -42,13 +37,12 @@ import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.ProcessBean; import javax.inject.Qualifier; -import org.apache.geode.cache.Region; - import org.junit.Before; import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; +import org.apache.geode.cache.Region; + import org.springframework.data.gemfire.mapping.GemfireMappingContext; import org.springframework.data.gemfire.repository.GemfireRepository; @@ -76,28 +70,32 @@ public class GemfireRepositoryExtensionTest { } protected Set asSet(T... array) { - return new HashSet(Arrays.asList(array)); + return new HashSet<>(Arrays.asList(array)); } - protected Annotation mockAnnotation(Class annotationType) { + @SuppressWarnings("rawtypes") + private Annotation mockAnnotation(Class annotationType) { Annotation mockAnnotation = mock(Annotation.class); when(mockAnnotation.annotationType()).thenReturn(annotationType); return mockAnnotation; } @Test + @SuppressWarnings("rawtypes") public void processBeanIdentifiesAndProcessesRegionBeanCorrectly() { + ProcessBean mockProcessBean = mock(ProcessBean.class); + Bean mockBean = mock(Bean.class); when(mockProcessBean.getBean()).thenReturn(mockBean); - when(mockBean.getTypes()).thenReturn(Collections.singleton((Type) Region.class)); + when(mockBean.getTypes()).thenReturn(Collections.singleton(Region.class)); - assertThat(repositoryExtension.regionBeans.isEmpty(), is(true)); + assertThat(repositoryExtension.regionBeans.isEmpty()).isTrue(); repositoryExtension.processBean(mockProcessBean); - assertThat(repositoryExtension.regionBeans.contains(mockBean), is(true)); + assertThat(repositoryExtension.regionBeans.contains(mockBean)).isTrue(); verify(mockProcessBean, times(1)).getBean(); verify(mockBean, times(1)).getTypes(); @@ -112,15 +110,15 @@ public class GemfireRepositoryExtensionTest { mockAnnotation(GemfireRepo.class)); when(mockProcessBean.getBean()).thenReturn(mockBean); - when(mockBean.getTypes()).thenReturn(Collections.singleton((Type) GemfireMappingContext.class)); + when(mockBean.getTypes()).thenReturn(Collections.singleton(GemfireMappingContext.class)); when(mockBean.getQualifiers()).thenReturn(expectedQualifiers); - assertThat(repositoryExtension.mappingContexts.isEmpty(), is(true)); + assertThat(repositoryExtension.mappingContexts.isEmpty()).isTrue(); repositoryExtension.processBean(mockProcessBean); - assertThat(repositoryExtension.mappingContexts.containsKey(expectedQualifiers), is(true)); - assertThat(repositoryExtension.mappingContexts.get(expectedQualifiers), is(equalTo(mockBean))); + assertThat(repositoryExtension.mappingContexts.containsKey(expectedQualifiers)).isTrue(); + assertThat(repositoryExtension.mappingContexts.get(expectedQualifiers)).isEqualTo(mockBean); verify(mockProcessBean, times(1)).getBean(); verify(mockBean, times(2)).getTypes(); @@ -133,15 +131,15 @@ public class GemfireRepositoryExtensionTest { Bean mockBean = mock(Bean.class); when(mockProcessBean.getBean()).thenReturn(mockBean); - when(mockBean.getTypes()).thenReturn(Collections.singleton((Type) Object.class)); + when(mockBean.getTypes()).thenReturn(Collections.singleton(Object.class)); - assertThat(repositoryExtension.mappingContexts.isEmpty(), is(true)); - assertThat(repositoryExtension.regionBeans.isEmpty(), is(true)); + assertThat(repositoryExtension.mappingContexts.isEmpty()).isTrue(); + assertThat(repositoryExtension.regionBeans.isEmpty()).isTrue(); repositoryExtension.processBean(mockProcessBean); - assertThat(repositoryExtension.mappingContexts.isEmpty(), is(true)); - assertThat(repositoryExtension.regionBeans.isEmpty(), is(true)); + assertThat(repositoryExtension.mappingContexts.isEmpty()).isTrue(); + assertThat(repositoryExtension.regionBeans.isEmpty()).isTrue(); verify(mockProcessBean, times(1)).getBean(); verify(mockBean, times(1)).getTypes(); @@ -154,20 +152,21 @@ public class GemfireRepositoryExtensionTest { final Set expectedQualifiers = asSet(mockAnnotation(SpringDataRepo.class), mockAnnotation(GemfireRepo.class)); - doAnswer(new Answer() { - public Void answer(final InvocationOnMock invocation) throws Throwable { - GemfireRepositoryBean repositoryBean = invocation.getArgument(0); + doAnswer((Answer) invocation -> { - assertThat(repositoryBean, is(notNullValue())); - assertThat((Class) repositoryBean.getBeanClass(), is(equalTo(TestRepository.class))); - assertThat(repositoryBean.getQualifiers(), is(equalTo(expectedQualifiers))); + GemfireRepositoryBean repositoryBean = invocation.getArgument(0); - return null; - } + assertThat(repositoryBean).isNotNull(); + assertThat(repositoryBean.getBeanClass()).isEqualTo(TestRepository.class); + assertThat(repositoryBean.getQualifiers()).isEqualTo(expectedQualifiers); + + return null; }).when(mockAfterBeanDiscovery).addBean(isA(GemfireRepositoryBean.class)); GemfireRepositoryExtension repositoryExtension = new GemfireRepositoryExtension() { - @Override protected Iterable, Set>> getRepositoryTypes() { + + @Override + protected Iterable, Set>> getRepositoryTypes() { return Collections., Set>singletonMap(TestRepository.class, expectedQualifiers).entrySet(); } }; @@ -178,16 +177,13 @@ public class GemfireRepositoryExtensionTest { } @Qualifier - @interface GemfireRepo { - } + @interface GemfireRepo { } @Qualifier - @interface SpringDataRepo { - } + @interface SpringDataRepo { } @GemfireRepo @SpringDataRepo - interface TestRepository extends GemfireRepository { - } + interface TestRepository extends GemfireRepository { } } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/query/PredicatesUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/query/PredicatesUnitTests.java index d9034d12..00246a3d 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/query/PredicatesUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/query/PredicatesUnitTests.java @@ -15,10 +15,7 @@ */ package org.springframework.data.gemfire.repository.query; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collections; @@ -30,27 +27,31 @@ import org.springframework.data.gemfire.repository.query.Predicates.AtomicPredic import org.springframework.data.repository.query.parser.Part; /** - * Unit tests for {@link Predicates}. + * Unit Tests for {@link Predicates}. * * @author Oliver Gierke * @author John Blum + * @see org.junit.Test + * @see org.springframework.data.gemfire.repository.query.Predicates */ @SuppressWarnings("unused") public class PredicatesUnitTests { @Test public void atomicPredicateDefaultsAlias() { + Part part = new Part("firstname", Person.class); Iterator indexes = Collections.singletonList(1).iterator(); Predicate predicate = new AtomicPredicate(part, indexes); - assertThat(predicate.toString(null), is("x.firstname = $1")); + assertThat(predicate.toString(null)).isEqualTo("x.firstname = $1"); } @Test public void concatenatesAndPredicateCorrectly() { + Part left = new Part("firstname", Person.class); Part right = new Part("lastname", Person.class); @@ -58,12 +59,13 @@ public class PredicatesUnitTests { Predicate predicate = Predicates.create(left, indexes).and(Predicates.create(right, indexes)); - assertThat(predicate, is(notNullValue(Predicate.class))); - assertThat(predicate.toString(null), is("x.firstname = $1 AND x.lastname = $2")); + assertThat(predicate).isNotNull(); + assertThat(predicate.toString(null)).isEqualTo("x.firstname = $1 AND x.lastname = $2"); } @Test public void concatenatesOrPredicateCorrectly() { + Part left = new Part("firstname", Person.class); Part right = new Part("lastname", Person.class); @@ -71,20 +73,21 @@ public class PredicatesUnitTests { Predicate predicate = Predicates.create(left, indexes).or(Predicates.create(right, indexes)); - assertThat(predicate, is(notNullValue(Predicate.class))); - assertThat(predicate.toString(null), is(equalTo("x.firstname = $1 OR x.lastname = $2"))); + assertThat(predicate).isNotNull(); + assertThat(predicate.toString(null)).isEqualTo("x.firstname = $1 OR x.lastname = $2"); } @Test public void handlesBooleanBasedPredicateCorrectly() { + Part part = new Part("activeTrue", User.class); Iterator indexes = Collections.singletonList(1).iterator(); Predicates predicate = Predicates.create(part, indexes); - assertThat(predicate, is(notNullValue(Predicate.class))); - assertThat(predicate.toString("user"), is(equalTo("user.active = true"))); + assertThat(predicate).isNotNull(); + assertThat(predicate.toString("user")).isEqualTo("user.active = true"); } /** @@ -92,6 +95,7 @@ public class PredicatesUnitTests { */ @Test public void handlesIgnoreCasePredicateCorrectly() { + Part left = new Part("firstnameIgnoreCase", Person.class); Part right = new Part("lastnameIgnoreCase", Person.class); @@ -99,8 +103,9 @@ public class PredicatesUnitTests { Predicate predicate = Predicates.create(left, indexes).and(Predicates.create(right, indexes)); - assertThat(predicate, is(notNullValue(Predicate.class))); - assertThat(predicate.toString("person"), is(equalTo("person.firstname.equalsIgnoreCase($1) AND person.lastname.equalsIgnoreCase($2)"))); + assertThat(predicate).isNotNull(); + assertThat(predicate.toString("person")) + .isEqualTo("person.firstname.equalsIgnoreCase($1) AND person.lastname.equalsIgnoreCase($2)"); } static class Person { diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/support/AbstractGemfireRepositoryFactoryIntegrationTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/support/AbstractGemfireRepositoryFactoryIntegrationTests.java index caffc694..a04e9418 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/support/AbstractGemfireRepositoryFactoryIntegrationTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/support/AbstractGemfireRepositoryFactoryIntegrationTests.java @@ -13,26 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire.repository.support; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.Arrays; import java.util.List; -import org.apache.geode.cache.Region; - -import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.apache.geode.cache.Region; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.data.gemfire.GemfireTemplate; @@ -40,17 +34,25 @@ import org.springframework.data.gemfire.mapping.GemfireMappingContext; import org.springframework.data.gemfire.mapping.Regions; import org.springframework.data.gemfire.repository.sample.Person; import org.springframework.data.gemfire.repository.sample.PersonRepository; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.data.gemfire.tests.integration.IntegrationTestsSupport; +import org.springframework.test.context.junit4.SpringRunner; + /** - * Integration test for {@link GemfireRepositoryFactory}. + * Integration Tests for {@link GemfireRepositoryFactory}. * * @author Oliver Gierke + * @author John Blum + * @see org.junit.Test + * @see org.apache.geode.cache.Region + * @see org.springframework.data.gemfire.repository.support.GemfireRepositoryFactory + * @see org.springframework.data.gemfire.tests.integration.IntegrationTestsSupport + * @see org.springframework.test.context.junit4.SpringRunner */ - -@RunWith(SpringJUnit4ClassRunner.class) -public abstract class AbstractGemfireRepositoryFactoryIntegrationTests { +@RunWith(SpringRunner.class) +public abstract class AbstractGemfireRepositoryFactoryIntegrationTests extends IntegrationTestsSupport { @Autowired + @SuppressWarnings("unused") private List> regions; private Person boyd; @@ -65,6 +67,7 @@ public abstract class AbstractGemfireRepositoryFactoryIntegrationTests { @Before public void setUp() { + dave = new Person(1L, "Dave", "Matthews"); carter = new Person(2L, "Carter", "Beauford"); boyd = new Person(3L, "Boyd", "Tinsley"); @@ -118,9 +121,6 @@ public abstract class AbstractGemfireRepositoryFactoryIntegrationTests { assertResultsFound(repository.findByFirstnameOrLastname("Carter", "Matthews"), carter, dave, oliverAugust); } - /** - * @see SGF-101 - */ @Test public void deletesAllEntitiesFromRegions() { @@ -129,25 +129,16 @@ public abstract class AbstractGemfireRepositoryFactoryIntegrationTests { assertResultsFound(repository.findAll()); } - /** - * @see SGF-113 - */ @Test public void findsPersonByLastname() { - assertThat(repository.findByLastname("Beauford"), is(carter)); + assertThat(repository.findByLastname("Beauford")).isEqualTo(carter); } - /** - * @see SGF-113 - */ @Test public void returnsNullForEmptyResultForSingleEntityQuery() { - assertThat(repository.findByLastname("Foo"), is(nullValue())); + assertThat(repository.findByLastname("Foo")).isNull(); } - /** - * @see SGF-113 - */ @Test public void throwsExceptionForMoreThanOneResultForSingleEntityQuery() { @@ -155,38 +146,26 @@ public abstract class AbstractGemfireRepositoryFactoryIntegrationTests { repository.findByLastname("Matthews"); fail("Exception expected!"); } catch (IncorrectResultSizeDataAccessException e) { - assertThat(e.getExpectedSize(), is(1)); - assertThat(e.getActualSize(), is(2)); + assertThat(e.getExpectedSize()).isEqualTo(1); + assertThat(e.getActualSize()).isEqualTo(2); } } - /** - * @see SGF-115 - */ @Test public void executesStartsWithCorrectly() { assertResultsFound(repository.findByFirstnameStartingWith("Da"), dave); } - /** - * @see SGF-115 - */ @Test public void executesEndsWithCorrectly() { assertResultsFound(repository.findByLastnameEndingWith("ews"), dave, oliverAugust); } - /** - * @see SGF-115 - */ @Test public void executesContainsCorrectly() { assertResultsFound(repository.findByFirstnameContaining("o"), boyd, leroi); } - /** - * @see SGF-115 - */ @Test public void executesLikeCorrectly() { assertResultsFound(repository.findByFirstnameLike("Da%"), dave); @@ -194,11 +173,12 @@ public abstract class AbstractGemfireRepositoryFactoryIntegrationTests { @SafeVarargs private static void assertResultsFound(Iterable result, T... expected) { - assertThat(result, is(notNullValue())); - assertThat(result, is(Matchers.iterableWithSize(expected.length))); + + assertThat(result).isNotNull(); + assertThat(result).hasSize(expected.length); for (T element : expected) { - assertThat(result, hasItem(element)); + assertThat(result).contains(element); } } } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/search/lucene/LuceneAccessorUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/search/lucene/LuceneAccessorUnitTests.java index bf5caf6a..96bfb053 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/search/lucene/LuceneAccessorUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/search/lucene/LuceneAccessorUnitTests.java @@ -14,16 +14,11 @@ * limitations under the License. * */ - package org.springframework.data.gemfire.search.lucene; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.isA; -import static org.hamcrest.Matchers.nullValue; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -33,6 +28,12 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.data.gemfire.search.lucene.LuceneAccessor.LuceneQueryExecutor; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + import org.apache.geode.cache.GemFireCache; import org.apache.geode.cache.Region; import org.apache.geode.cache.lucene.LuceneIndex; @@ -40,14 +41,6 @@ import org.apache.geode.cache.lucene.LuceneQueryException; import org.apache.geode.cache.lucene.LuceneQueryFactory; import org.apache.geode.cache.lucene.LuceneService; -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.junit.MockitoJUnitRunner; - import org.springframework.dao.DataRetrievalFailureException; import org.springframework.data.gemfire.search.lucene.support.LuceneAccessorSupport; @@ -68,9 +61,6 @@ import org.springframework.data.gemfire.search.lucene.support.LuceneAccessorSupp @RunWith(MockitoJUnitRunner.class) public class LuceneAccessorUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - @Mock private GemFireCache mockCache; @@ -133,8 +123,8 @@ public class LuceneAccessorUnitTests { } @Test - @SuppressWarnings("deprecation") public void createLuceneQueryFactoryWithResultLimit() { + doReturn(mockLuceneService).when(luceneAccessor).resolveLuceneService(); when(mockLuceneService.createLuceneQueryFactory()).thenReturn(mockLuceneQueryFactory); when(mockLuceneQueryFactory.setPageSize(anyInt())).thenReturn(mockLuceneQueryFactory); @@ -150,8 +140,8 @@ public class LuceneAccessorUnitTests { } @Test - @SuppressWarnings("deprecation") public void createLuceneQueryFactoryWithResultLimitAndPageSize() { + doReturn(mockLuceneService).when(luceneAccessor).resolveLuceneService(); when(mockLuceneService.createLuceneQueryFactory()).thenReturn(mockLuceneQueryFactory); when(mockLuceneQueryFactory.setPageSize(anyInt())).thenReturn(mockLuceneQueryFactory); @@ -168,6 +158,7 @@ public class LuceneAccessorUnitTests { @Test public void resolveCacheReturnsConfiguredCache() { + luceneAccessor.setCache(mockCache); assertThat(luceneAccessor.getCache()).isSameAs(mockCache); @@ -176,6 +167,7 @@ public class LuceneAccessorUnitTests { @Test public void resolveLuceneServiceReturnsConfiguredLuceneService() { + luceneAccessor.setLuceneService(mockLuceneService); assertThat(luceneAccessor.getLuceneService()).isSameAs(mockLuceneService); @@ -184,7 +176,7 @@ public class LuceneAccessorUnitTests { @Test public void resolveLuceneServiceLooksUpLuceneService() { - doReturn(mockCache).when(luceneAccessor).resolveCache(); + doReturn(mockLuceneService).when(luceneAccessor).resolveLuceneService(eq(mockCache)); assertThat(luceneAccessor.getLuceneService()).isNull(); @@ -196,16 +188,22 @@ public class LuceneAccessorUnitTests { @Test public void resolveLuceneServiceThrowsIllegalArgumentExceptionWhenCacheIsNull() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("Cache reference was not properly configured"); - luceneAccessor.resolveLuceneService(null); + try { + luceneAccessor.resolveLuceneService(null); + } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("Cache reference was not properly configured"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test - @SuppressWarnings("all") public void resolveIndexNameReturnsConfiguredIndexName() { + luceneAccessor.setIndexName("TestIndex"); assertThat(luceneAccessor.getIndexName()).isEqualTo("TestIndex"); @@ -215,8 +213,8 @@ public class LuceneAccessorUnitTests { } @Test - @SuppressWarnings("all") public void resolveIndexNameReturnsLuceneIndexName() { + luceneAccessor.setLuceneIndex(mockLuceneIndex); when(mockLuceneIndex.getName()).thenReturn("MockIndex"); @@ -229,20 +227,26 @@ public class LuceneAccessorUnitTests { } @Test - @SuppressWarnings("all") public void resolveIndexNameThrowsIllegalStateExceptionWhenIndexNameIsUnresolvable() { + assertThat(luceneAccessor.getIndexName()).isNullOrEmpty(); assertThat(luceneAccessor.getLuceneIndex()).isNull(); - exception.expect(IllegalStateException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("The name of the Lucene Index could not be resolved"); + try { + luceneAccessor.resolveIndexName(); + } + catch (IllegalStateException expected) { - luceneAccessor.resolveIndexName(); + assertThat(expected).hasMessage("The name of the Lucene Index could not be resolved"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void resolveRegionPathReturnsConfiguredRegionPath() { + luceneAccessor.setRegionPath("/Example"); assertThat(luceneAccessor.getRegionPath()).isEqualTo("/Example"); @@ -250,8 +254,8 @@ public class LuceneAccessorUnitTests { } @Test - @SuppressWarnings("all") public void resolveRegionPathReturnsRegionFullPath() { + when(mockRegion.getFullPath()).thenReturn("/Example"); luceneAccessor.setRegion(mockRegion); @@ -263,21 +267,28 @@ public class LuceneAccessorUnitTests { verify(mockRegion, times(1)).getFullPath(); } - @Test + @Test(expected = IllegalStateException.class) public void resolveRegionPathThrowsIllegalStatueExceptionWhenRegionPathIsUnresolvable() { + assertThat(luceneAccessor.getRegion()).isNull(); assertThat(luceneAccessor.getRegionPath()).isNullOrEmpty(); - exception.expect(IllegalStateException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("Region path could not be resolved"); + try { + luceneAccessor.resolveRegionPath(); + } + catch (IllegalStateException expected) { - luceneAccessor.resolveRegionPath(); + assertThat(expected).hasMessage("Region path could not be resolved"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test @SuppressWarnings("unchecked") public void doFind() throws LuceneQueryException { + LuceneQueryExecutor mockQueryExecutor = mock(LuceneQueryExecutor.class); when(mockQueryExecutor.execute()).thenReturn("test"); @@ -288,22 +299,27 @@ public class LuceneAccessorUnitTests { verify(mockQueryExecutor, times(1)).execute(); } - @Test + @Test(expected = DataRetrievalFailureException.class) @SuppressWarnings("unchecked") public void doFindHandlesLuceneQueryException() throws LuceneQueryException { + LuceneQueryExecutor mockQueryExecutor = mock(LuceneQueryExecutor.class); when(mockQueryExecutor.execute()).thenThrow(new LuceneQueryException("test")); try { - exception.expect(DataRetrievalFailureException.class); - exception.expectCause(isA(LuceneQueryException.class)); - exception.expectMessage(containsString( - "Failed to execute Lucene Query [title : Up Shit Creek Without a Paddle] on Region [/Example] with Lucene Index [ExampleIndex]")); - luceneAccessor.doFind(mockQueryExecutor, "title : Up Shit Creek Without a Paddle", "/Example", "ExampleIndex"); } + catch (DataRetrievalFailureException expected) { + + assertThat(expected) + .hasMessageContaining("Failed to execute Lucene Query [title : Up Shit Creek Without a Paddle] on Region [/Example] with Lucene Index [ExampleIndex]"); + + assertThat(expected).hasCauseInstanceOf(LuceneQueryException.class); + + throw expected; + } finally { verify(mockQueryExecutor, times(1)).execute(); } @@ -311,6 +327,7 @@ public class LuceneAccessorUnitTests { @Test public void luceneAccessorInitializedCorrectly() { + luceneAccessor.setCache(mockCache); luceneAccessor.setIndexName("ExampleIndex"); luceneAccessor.setLuceneIndex(mockLuceneIndex); diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/search/lucene/LuceneServiceFactoryBeanUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/search/lucene/LuceneServiceFactoryBeanUnitTests.java index 27137419..cd6537de 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/search/lucene/LuceneServiceFactoryBeanUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/search/lucene/LuceneServiceFactoryBeanUnitTests.java @@ -14,36 +14,29 @@ * limitations under the License. * */ - package org.springframework.data.gemfire.search.lucene; -import static org.assertj.core.api.Java6Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.mockito.Matchers.eq; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import org.apache.geode.cache.GemFireCache; -import org.apache.geode.cache.lucene.LuceneService; - 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.junit.MockitoJUnitRunner; +import org.apache.geode.cache.GemFireCache; +import org.apache.geode.cache.lucene.LuceneService; + /** - * Unit tests for {@link LuceneServiceFactoryBean}. + * Unit Tests for {@link LuceneServiceFactoryBean}. * * @author John Blum - * @see org.junit.Rule * @see org.junit.Test - * @see org.junit.runner.RunWith * @see org.mockito.Mock * @see org.mockito.Mockito * @see org.mockito.Spy @@ -54,9 +47,6 @@ import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class LuceneServiceFactoryBeanUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - @Mock private GemFireCache mockCache; @@ -73,6 +63,7 @@ public class LuceneServiceFactoryBeanUnitTests { @Test public void setAndGetCache() { + assertThat(factoryBean.getCache()).isNull(); factoryBean.setCache(mockCache); @@ -86,6 +77,7 @@ public class LuceneServiceFactoryBeanUnitTests { @Test public void afterPropertiesSetInitializesLuceneService() throws Exception { + assertThat(factoryBean.getObject()).isNull(); factoryBean.setCache(mockCache); @@ -96,25 +88,33 @@ public class LuceneServiceFactoryBeanUnitTests { verify(factoryBean, times(1)).resolveLuceneService(eq(mockCache)); } - @Test + @Test(expected = IllegalStateException.class) public void afterPropertiesSetThrowsIllegalStateExceptionWhenGemFireCacheIsNull() throws Exception { + assertThat(factoryBean.getCache()).isNull(); - exception.expect(IllegalStateException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("A reference to the GemFireCache was not properly configured"); + try { + factoryBean.afterPropertiesSet(); + } + catch (IllegalStateException expected) { - factoryBean.afterPropertiesSet(); + assertThat(expected).hasMessage("A reference to the GemFireCache was not properly configured"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void getObjectTypeBeforeInitialization() throws Exception { + assertThat(factoryBean.getObject()).isNull(); assertThat(factoryBean.getObjectType()).isEqualTo(LuceneService.class); } @Test public void getObjectTypeAfterInitialization() throws Exception { + factoryBean.setCache(mockCache); factoryBean.afterPropertiesSet(); diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/server/SubscriptionEvictionPolicyConverterUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/server/SubscriptionEvictionPolicyConverterUnitTests.java index fa01b0a1..babae3fe 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/server/SubscriptionEvictionPolicyConverterUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/server/SubscriptionEvictionPolicyConverterUnitTests.java @@ -13,17 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire.server; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** * Unit tests for {@link SubscriptionEvictionPolicyConverter}. @@ -36,9 +31,6 @@ import org.junit.rules.ExpectedException; */ public class SubscriptionEvictionPolicyConverterUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - private final SubscriptionEvictionPolicyConverter converter = new SubscriptionEvictionPolicyConverter(); @After @@ -48,36 +40,54 @@ public class SubscriptionEvictionPolicyConverterUnitTests { @Test public void convert() { + assertThat(converter.convert("EnTry")).isEqualTo(SubscriptionEvictionPolicy.ENTRY); assertThat(converter.convert("MEM")).isEqualTo(SubscriptionEvictionPolicy.MEM); assertThat(converter.convert("nONE")).isEqualTo(SubscriptionEvictionPolicy.NONE); assertThat(converter.convert("NOne")).isEqualTo(SubscriptionEvictionPolicy.NONE); } - @Test + @Test(expected = IllegalArgumentException.class) public void convertIllegalValue() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[memory] is not a valid SubscriptionEvictionPolicy"); - converter.setAsText("memory"); + try { + converter.setAsText("memory"); + } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[memory] is not a valid SubscriptionEvictionPolicy"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void setAsText() { + assertThat(converter.getValue()).isNull(); + converter.setAsText("enTRY"); + assertThat(converter.getValue()).isEqualTo(SubscriptionEvictionPolicy.ENTRY); + converter.setAsText("MEm"); + assertThat(converter.getValue()).isEqualTo(SubscriptionEvictionPolicy.MEM); } - @Test + @Test(expected = IllegalArgumentException.class) public void setAsTextWithIllegalValue() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[KEYS] is not a valid SubscriptionEvictionPolicy"); - converter.setAsText("KEYS"); + try { + converter.setAsText("KEYS"); + } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[KEYS] is not a valid SubscriptionEvictionPolicy"); + assertThat(expected).hasNoCause(); + + throw expected; + } } } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointListTest.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointListTest.java index 58440989..38335316 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointListTest.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointListTest.java @@ -13,32 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire.support; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -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.assertj.core.api.Assertions.assertThat; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** - * The ConnectionEndpointListTest class is a test suite of test cases testing the contract and functionality - * of the ConnectionEndpointList class. + * Unit Tests for {@link ConnectionEndpointList}. * * @author John Blum * @see java.net.InetSocketAddress - * @see org.junit.Rule * @see org.junit.Test * @see org.junit.rules.ExpectedException * @see org.springframework.data.gemfire.support.ConnectionEndpoint @@ -47,23 +37,22 @@ import org.junit.rules.ExpectedException; */ public class ConnectionEndpointListTest { - @Rule - public ExpectedException exception = ExpectedException.none(); - - protected ConnectionEndpoint newConnectionEndpoint(String host, int port) { + private ConnectionEndpoint newConnectionEndpoint(String host, int port) { return new ConnectionEndpoint(host, port); } @Test public void constructNewEmptyConnectionEndpointList() { + ConnectionEndpointList connectionEndpoints = new ConnectionEndpointList(); - assertThat(connectionEndpoints.isEmpty(), is(true)); - assertThat(connectionEndpoints.size(), is(equalTo(0))); + assertThat(connectionEndpoints.isEmpty()).isTrue(); + assertThat(connectionEndpoints.size()).isEqualTo(0); } @Test public void constructNewInitializedConnectionEndpointList() { + ConnectionEndpoint[] connectionEndpoints = { newConnectionEndpoint("jambox", 1234), newConnectionEndpoint("skullbox", 9876) @@ -71,18 +60,19 @@ public class ConnectionEndpointListTest { ConnectionEndpointList connectionEndpointList = new ConnectionEndpointList(connectionEndpoints); - assertThat(connectionEndpointList.isEmpty(), is(false)); - assertThat(connectionEndpointList.size(), is(equalTo(connectionEndpoints.length))); + assertThat(connectionEndpointList.isEmpty()).isFalse(); + assertThat(connectionEndpointList.size()).isEqualTo(connectionEndpoints.length); int index = 0; for (ConnectionEndpoint connectionEndpoint : connectionEndpointList) { - assertThat(connectionEndpoint, is(equalTo(connectionEndpoints[index++]))); + assertThat(connectionEndpoint).isEqualTo(connectionEndpoints[index++]); } } @Test public void fromConnectionEndpoints() { + ConnectionEndpoint[] connectionEndpoints = { newConnectionEndpoint("boombox", 10334), newConnectionEndpoint("skullbox", 40404), @@ -91,18 +81,19 @@ public class ConnectionEndpointListTest { ConnectionEndpointList list = ConnectionEndpointList.from(connectionEndpoints); - assertThat(list, is(notNullValue())); - assertThat(list.size(), is(equalTo(connectionEndpoints.length))); + assertThat(list).isNotNull(); + assertThat(list.size()).isEqualTo(connectionEndpoints.length); int index = 0; for (ConnectionEndpoint connectionEndpoint : list) { - assertThat(connectionEndpoint, is(equalTo(connectionEndpoints[index++]))); + assertThat(connectionEndpoint).isEqualTo(connectionEndpoints[index++]); } } @Test public void fromInetSocketAddresses() { + InetSocketAddress[] inetSocketAddresses = { new InetSocketAddress("localhost", 1234), new InetSocketAddress("localhost", 9876) @@ -110,58 +101,63 @@ public class ConnectionEndpointListTest { ConnectionEndpointList list = ConnectionEndpointList.from(inetSocketAddresses); - assertThat(list, is(notNullValue())); - assertThat(list.size(), is(equalTo(inetSocketAddresses.length))); + assertThat(list).isNotNull(); + assertThat(list.size()).isEqualTo(inetSocketAddresses.length); int index = 0; for (ConnectionEndpoint connectionEndpoint : list) { - assertThat(connectionEndpoint.getHost(), is(equalTo(inetSocketAddresses[index].getHostString()))); - assertThat(connectionEndpoint.getPort(), is(equalTo(inetSocketAddresses[index++].getPort()))); + assertThat(connectionEndpoint.getHost()).isEqualTo(inetSocketAddresses[index].getHostString()); + assertThat(connectionEndpoint.getPort()).isEqualTo(inetSocketAddresses[index++].getPort()); } } @Test - @SuppressWarnings("unchecked") + @SuppressWarnings({ "rawtypes", "unchecked" }) public void fromIterableInetSocketAddressesIsNullSafe() { + ConnectionEndpointList list = ConnectionEndpointList.from((Iterable) null); - assertThat(list, is(notNullValue())); - assertThat(list.isEmpty(), is(true)); + assertThat(list).isNotNull(); + assertThat(list.isEmpty()).isTrue(); } @Test public void parse() { - ConnectionEndpointList list = ConnectionEndpointList.parse(24842, "mercury[11235]", "venus", "[12480]", "[]", - "jupiter[]", "saturn[1, 2-Hundred and 34.zero5]", "neptune[four]"); + + ConnectionEndpointList list = + ConnectionEndpointList.parse(24842, "mercury[11235]", "venus", "[12480]", "[]", + "jupiter[]", "saturn[1, 2-Hundred and 34.zero5]", "neptune[four]"); String[] expectedHostPorts = { "mercury[11235]", "venus[24842]", "localhost[12480]", "localhost[24842]", "jupiter[24842]", "saturn[12345]", "neptune[24842]" }; - assertThat(list, is(notNullValue())); - assertThat(list.size(), is(equalTo(expectedHostPorts.length))); + assertThat(list).isNotNull(); + assertThat(list.size()).isEqualTo(expectedHostPorts.length); int index = 0; for (ConnectionEndpoint connectionEndpoint : list) { - assertThat(connectionEndpoint.toString(), is(equalTo(expectedHostPorts[index++]))); + assertThat(connectionEndpoint.toString()).isEqualTo(expectedHostPorts[index++]); } } @Test public void parseWithEmptyHostsPortsArgument() { + ConnectionEndpointList list = ConnectionEndpointList.parse(1234); - assertThat(list, is(notNullValue())); - assertThat(list.isEmpty(), is(true)); + assertThat(list).isNotNull(); + assertThat(list.isEmpty()).isTrue(); } @Test - @SuppressWarnings("unchecked") + @SuppressWarnings({ "rawtypes", "unchecked" }) public void addAdditionalConnectionEndpoints() { + ConnectionEndpointList list = new ConnectionEndpointList(); - assertThat(list.isEmpty(), is(true)); + assertThat(list.isEmpty()).isTrue(); ConnectionEndpoint[] connectionEndpointsArray = { newConnectionEndpoint("Mercury", 1111) }; @@ -176,10 +172,9 @@ public class ConnectionEndpointListTest { newConnectionEndpoint("Pluto", 9999) ); - assertThat(list.add(connectionEndpointsArray).add(connectionEndpointsIterable), - is(sameInstance(list))); + assertThat(list.add(connectionEndpointsArray).add(connectionEndpointsIterable)).isSameAs(list); - List expected = new ArrayList(9); + List expected = new ArrayList<>(9); expected.add(connectionEndpointsArray[0]); expected.addAll((List) connectionEndpointsIterable); @@ -187,12 +182,13 @@ public class ConnectionEndpointListTest { int index = 0; for (ConnectionEndpoint connectionEndpoint : list) { - assertThat(connectionEndpoint, is(equalTo(expected.get(index++)))); + assertThat(connectionEndpoint).isEqualTo(expected.get(index++)); } } @Test public void findByHostName() { + ConnectionEndpointList list = new ConnectionEndpointList( newConnectionEndpoint("Earth", 10334), newConnectionEndpoint("Earth", 40404), @@ -202,37 +198,38 @@ public class ConnectionEndpointListTest { newConnectionEndpoint("Neptune", 12345) ); - assertThat(list.size(), is(equalTo(6))); + assertThat(list.size()).isEqualTo(6); ConnectionEndpointList result = list.findBy("Earth"); - assertThat(result, is(notNullValue())); - assertThat(result.size(), is(equalTo(2))); + assertThat(result).isNotNull(); + assertThat(result.size()).isEqualTo(2); String[] expected = { "Earth[10334]", "Earth[40404]" }; int index = 0; for (ConnectionEndpoint connectionEndpoint : result) { - assertThat(connectionEndpoint.toString(), is(equalTo(expected[index++]))); + assertThat(connectionEndpoint.toString()).isEqualTo(expected[index++]); } result = list.findBy("Saturn"); - assertThat(result, is(notNullValue())); - assertThat(result.isEmpty(), is(false)); - assertThat(result.size(), is(equalTo(1))); - assertThat(result.iterator().next().toString(), is(equalTo("Saturn[9876]"))); + assertThat(result).isNotNull(); + assertThat(result.isEmpty()).isFalse(); + assertThat(result.size()).isEqualTo(1); + assertThat(result.iterator().next().toString()).isEqualTo("Saturn[9876]"); result = list.findBy("Pluto"); - assertThat(result, is(notNullValue())); - assertThat(result.isEmpty(), is(true)); - assertThat(result.size(), is(equalTo(0))); + assertThat(result).isNotNull(); + assertThat(result.isEmpty()).isTrue(); + assertThat(result.size()).isEqualTo(0); } @Test public void findByPortNumber() { + ConnectionEndpointList list = new ConnectionEndpointList( newConnectionEndpoint("Earth", 10334), newConnectionEndpoint("Earth", 40404), @@ -242,87 +239,90 @@ public class ConnectionEndpointListTest { newConnectionEndpoint("Neptune", 12345) ); - assertThat(list.size(), is(equalTo(6))); + assertThat(list.size()).isEqualTo(6); ConnectionEndpointList result = list.findBy(10334); - assertThat(result, is(notNullValue())); - assertThat(result.size(), is(equalTo(2))); + assertThat(result).isNotNull(); + assertThat(result.size()).isEqualTo(2); String[] expected = { "Earth[10334]", "Mars[10334]" }; int index = 0; for (ConnectionEndpoint connectionEndpoint : result) { - assertThat(connectionEndpoint.toString(), is(equalTo(expected[index++]))); + assertThat(connectionEndpoint.toString()).isEqualTo(expected[index++]); } result = list.findBy(1234); - assertThat(result, is(notNullValue())); - assertThat(result.size(), is(equalTo(1))); - assertThat(result.iterator().next().toString(), is(equalTo("Jupiter[1234]"))); + assertThat(result).isNotNull(); + assertThat(result.size()).isEqualTo(1); + assertThat(result.iterator().next().toString()).isEqualTo("Jupiter[1234]"); result = list.findBy(80); - assertThat(result, is(notNullValue())); - assertThat(result.isEmpty(), is(true)); + assertThat(result).isNotNull(); + assertThat(result.isEmpty()).isTrue(); } @Test public void findOneByHostName() { + ConnectionEndpointList list = new ConnectionEndpointList(); - assertThat(list.findOne("localhost"), is(nullValue())); + assertThat(list.findOne("localhost")).isNull(); list.add(newConnectionEndpoint("skullbox", 11235)); - assertThat(list.findOne("localhost"), is(nullValue())); - assertThat(list.findOne("skullbox"), is(equalTo(newConnectionEndpoint("skullbox", 11235)))); + assertThat(list.findOne("localhost")).isNull(); + assertThat(list.findOne("skullbox")).isEqualTo(newConnectionEndpoint("skullbox", 11235)); list.add(newConnectionEndpoint("toolbox", 12480)); - assertThat(list.findOne("boombox"), is(nullValue())); - assertThat(list.findOne("localhost"), is(nullValue())); - assertThat(list.findOne("skullbox"), is(equalTo(newConnectionEndpoint("skullbox", 11235)))); - assertThat(list.findOne("toolbox"), is(equalTo(newConnectionEndpoint("toolbox", 12480)))); + assertThat(list.findOne("boombox")).isNull(); + assertThat(list.findOne("localhost")).isNull(); + assertThat(list.findOne("skullbox")).isEqualTo(newConnectionEndpoint("skullbox", 11235)); + assertThat(list.findOne("toolbox")).isEqualTo(newConnectionEndpoint("toolbox", 12480)); list.add(newConnectionEndpoint("skullbox", 10334)); - assertThat(list.findOne("localhost"), is(nullValue())); - assertThat(list.findOne("boombox"), is(nullValue())); - assertThat(list.findOne("skullbox"), is(equalTo(newConnectionEndpoint("skullbox", 11235)))); - assertThat(list.findOne("toolbox"), is(equalTo(newConnectionEndpoint("toolbox", 12480)))); + assertThat(list.findOne("localhost")).isNull(); + assertThat(list.findOne("boombox")).isNull(); + assertThat(list.findOne("skullbox")).isEqualTo(newConnectionEndpoint("skullbox", 11235)); + assertThat(list.findOne("toolbox")).isEqualTo(newConnectionEndpoint("toolbox", 12480)); } @Test public void findOneByPortNumber() { + ConnectionEndpointList list = new ConnectionEndpointList(); - assertThat(list.findOne(10334), is(nullValue())); + assertThat(list.findOne(10334)).isNull(); list.add(newConnectionEndpoint("skullbox", 11235)); - assertThat(list.findOne(10334), is(nullValue())); - assertThat(list.findOne(11235), is(equalTo(newConnectionEndpoint("skullbox", 11235)))); + assertThat(list.findOne(10334)).isNull(); + assertThat(list.findOne(11235)).isEqualTo(newConnectionEndpoint("skullbox", 11235)); list.add(newConnectionEndpoint("toolbox", 12480)); - assertThat(list.findOne(10334), is(nullValue())); - assertThat(list.findOne(40404), is(nullValue())); - assertThat(list.findOne(11235), is(equalTo(newConnectionEndpoint("skullbox", 11235)))); - assertThat(list.findOne(12480), is(equalTo(newConnectionEndpoint("toolbox", 12480)))); + assertThat(list.findOne(10334)).isNull(); + assertThat(list.findOne(40404)).isNull(); + assertThat(list.findOne(11235)).isEqualTo(newConnectionEndpoint("skullbox", 11235)); + assertThat(list.findOne(12480)).isEqualTo(newConnectionEndpoint("toolbox", 12480)); list.add(newConnectionEndpoint("boombox", 11235)); - assertThat(list.findOne(10334), is(nullValue())); - assertThat(list.findOne(40404), is(nullValue())); - assertThat(list.findOne(11235), is(equalTo(newConnectionEndpoint("skullbox", 11235)))); - assertThat(list.findOne(12480), is(equalTo(newConnectionEndpoint("toolbox", 12480)))); + assertThat(list.findOne(10334)).isNull(); + assertThat(list.findOne(40404)).isNull(); + assertThat(list.findOne(11235)).isEqualTo(newConnectionEndpoint("skullbox", 11235)); + assertThat(list.findOne(12480)).isEqualTo(newConnectionEndpoint("toolbox", 12480)); } @Test public void toArrayFromList() { + ConnectionEndpointList list = ConnectionEndpointList.from( newConnectionEndpoint("boombox", 11235), newConnectionEndpoint("skullbox", 12480), @@ -330,62 +330,65 @@ public class ConnectionEndpointListTest { ConnectionEndpoint[] connectionEndpointArray = list.toArray(); - assertThat(connectionEndpointArray, is(notNullValue())); - assertThat(connectionEndpointArray.length, is(equalTo(list.size()))); + assertThat(connectionEndpointArray).isNotNull(); + assertThat(connectionEndpointArray.length).isEqualTo(list.size()); int index = 0; for (ConnectionEndpoint connectionEndpoint : list) { - assertThat(connectionEndpointArray[index++], is(equalTo(connectionEndpoint))); + assertThat(connectionEndpointArray[index++]).isEqualTo(connectionEndpoint); } } @Test public void toArrayFromEmptyList() { + ConnectionEndpoint[] connectionEndpoints = new ConnectionEndpointList().toArray(); - assertThat(connectionEndpoints, is(notNullValue())); - assertThat(connectionEndpoints.length, is(equalTo(0))); + assertThat(connectionEndpoints).isNotNull(); + assertThat(connectionEndpoints.length).isEqualTo(0); } @Test public void toInetSocketAddressesFromList() { + ConnectionEndpointList list = ConnectionEndpointList.from( newConnectionEndpoint("localhost", 10334), newConnectionEndpoint("localhost", 40404)); List socketAddresses = list.toInetSocketAddresses(); - assertThat(socketAddresses, is(notNullValue())); - assertThat(socketAddresses.size(), is(equalTo(list.size()))); + assertThat(socketAddresses).isNotNull(); + assertThat(socketAddresses.size()).isEqualTo(list.size()); int index = 0; for (ConnectionEndpoint connectionEndpoint : list) { - assertThat(socketAddresses.get(index).getHostName(), is(equalTo(connectionEndpoint.getHost()))); - assertThat(socketAddresses.get(index++).getPort(), is(equalTo(connectionEndpoint.getPort()))); + assertThat(socketAddresses.get(index).getHostName()).isEqualTo(connectionEndpoint.getHost()); + assertThat(socketAddresses.get(index++).getPort()).isEqualTo(connectionEndpoint.getPort()); } } @Test public void toInetSocketAddressesFromEmptyList() { + List socketAddresses = new ConnectionEndpointList().toInetSocketAddresses(); - assertThat(socketAddresses, is(notNullValue())); - assertThat(socketAddresses.isEmpty(), is(true)); + assertThat(socketAddresses).isNotNull(); + assertThat(socketAddresses.isEmpty()).isTrue(); } @Test public void toStringFromList() { + ConnectionEndpointList list = ConnectionEndpointList.parse(10334, "skullbox[12480]", "saturn[ 1 12 3 5]", "neptune"); - assertThat(list.toString(), is(equalTo("[skullbox[12480], saturn[11235], neptune[10334]]"))); + assertThat(list.toString()).isEqualTo("[skullbox[12480], saturn[11235], neptune[10334]]"); } @Test public void toStringFromEmptyList() { - assertThat(new ConnectionEndpointList().toString(), is(equalTo("[]"))); + assertThat(new ConnectionEndpointList().toString()).isEqualTo("[]"); } - } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/DeclarableSupportUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/DeclarableSupportUnitTests.java index 0910982f..a3684dbe 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/DeclarableSupportUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/DeclarableSupportUnitTests.java @@ -14,19 +14,14 @@ * 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; @@ -35,10 +30,9 @@ import org.mockito.junit.MockitoJUnitRunner; import org.springframework.beans.factory.BeanFactory; /** - * Unit tests for {@link DeclarableSupport}. + * Unit Tests for {@link DeclarableSupport}. * * @author John Blum - * @see org.junit.Rule * @see org.junit.Test * @see org.mockito.Mock * @see org.mockito.Mockito @@ -49,9 +43,6 @@ import org.springframework.beans.factory.BeanFactory; @RunWith(MockitoJUnitRunner.class) public class DeclarableSupportUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - @Mock private BeanFactory mockBeanFactoryOne; @@ -111,6 +102,7 @@ public class DeclarableSupportUnitTests { @Test public void locateBeanFactoryWithUnknownKeyHavingMultipleBeanFactoriesRegisteredThrowsIllegalArgumentException() { + GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyOne", mockBeanFactoryOne); GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyTwo", mockBeanFactoryTwo); @@ -118,54 +110,81 @@ public class DeclarableSupportUnitTests { assertThat(testDeclarableSupport.getBeanFactoryKey()).isEqualTo("keyOne"); - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("BeanFactory for key [UnknownKey] was not found"); + try { + testDeclarableSupport.locateBeanFactory("UnknownKey"); + } + catch (IllegalArgumentException expected) { - testDeclarableSupport.locateBeanFactory("UnknownKey"); + assertThat(expected).hasMessage("BeanFactory for key [UnknownKey] was not found"); + assertThat(expected).hasNoCause(); + + throw expected; + } } - @Test + @Test(expected = IllegalStateException.class) 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"); + try { + testDeclarableSupport.locateBeanFactory(); + } + catch (IllegalStateException expected) { - testDeclarableSupport.locateBeanFactory(); + assertThat(expected) + .hasMessage("BeanFactory key must be specified when more than one BeanFactory [keyOne, keyTwo] is registered"); + + assertThat(expected).hasNoCause(); + + throw expected; + } } - @Test + @Test(expected = IllegalStateException.class) 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"); + try { + testDeclarableSupport.locateBeanFactory("testKey"); + } + catch (IllegalStateException expected) { - testDeclarableSupport.locateBeanFactory("testKey"); + assertThat(expected).hasMessage("A BeanFactory was not initialized;" + + " Please verify the useBeanFactoryLocator property was properly set"); + + assertThat(expected).hasNoCause(); + + throw expected; + } } - @Test + @Test(expected = IllegalStateException.class) 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"); + try { + testDeclarableSupport.locateBeanFactory(); + } + catch (IllegalStateException expected) { - testDeclarableSupport.locateBeanFactory(); + assertThat(expected).hasMessage("A BeanFactory was not initialized;" + + " Please verify the useBeanFactoryLocator property was properly set"); + + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void getBeanFactoryReturnsBeanFactory() { + GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyOne", mockBeanFactoryOne); GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyTwo", mockBeanFactoryTwo); @@ -177,7 +196,9 @@ public class DeclarableSupportUnitTests { @Test public void closeIsSuccessful() { + testDeclarableSupport.close(); + verify(testDeclarableSupport, times(1)).close(); } } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/GemfireBeanFactoryLocatorUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/GemfireBeanFactoryLocatorUnitTests.java index 43e6908a..b927f74e 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/GemfireBeanFactoryLocatorUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/GemfireBeanFactoryLocatorUnitTests.java @@ -14,18 +14,16 @@ * 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.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.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.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; 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; @@ -37,9 +35,7 @@ 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.junit.MockitoJUnitRunner; @@ -47,10 +43,9 @@ import org.mockito.junit.MockitoJUnitRunner; import org.springframework.beans.factory.BeanFactory; /** - * Unit tests for {@link GemfireBeanFactoryLocator}. + * Unit Tests for {@link GemfireBeanFactoryLocator}. * * @author John Blum - * @see org.junit.Rule * @see org.junit.Test * @see org.mockito.Mock * @see org.mockito.Mockito @@ -61,9 +56,6 @@ import org.springframework.beans.factory.BeanFactory; @RunWith(MockitoJUnitRunner.class) public class GemfireBeanFactoryLocatorUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - @Mock private BeanFactory mockBeanFactory; @@ -79,6 +71,7 @@ public class GemfireBeanFactoryLocatorUnitTests { @Test public void newUninitializedBeanFactorLocator() { + GemfireBeanFactoryLocator beanFactoryLocator = newBeanFactoryLocator(); assertThat(beanFactoryLocator).isNotNull(); @@ -90,6 +83,7 @@ public class GemfireBeanFactoryLocatorUnitTests { @Test public void newInitializedBeanFactoryLocator() { + when(mockBeanFactory.getAliases(anyString())).thenReturn(new String[0]); GemfireBeanFactoryLocator beanFactoryLocator = newBeanFactoryLocator(mockBeanFactory, "AssociatedBeanName"); @@ -106,6 +100,7 @@ public class GemfireBeanFactoryLocatorUnitTests { @Test public void newInitializedBeanFactoryLocatorWithNullBeanFactoryAndSpecifiedBeanName() { + GemfireBeanFactoryLocator beanFactoryLocator = newBeanFactoryLocator(null, "MyBeanName"); assertThat(beanFactoryLocator).isNotNull(); @@ -115,17 +110,24 @@ public class GemfireBeanFactoryLocatorUnitTests { assertThat(beanFactoryLocator.getAssociatedBeanNameWithAliases()).isEmpty(); } - @Test + @Test(expected = IllegalArgumentException.class) 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, " "); + try { + newBeanFactoryLocator(mockBeanFactory, " "); + } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("associatedBeanName must be specified when BeanFactory is not null"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void resolveBeanFactoryReturnsResolvedBeanFactory() { + GemfireBeanFactoryLocator.BEAN_FACTORIES.put("MyBeanKey", mockBeanFactory); assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES).hasSize(1); @@ -134,33 +136,42 @@ public class GemfireBeanFactoryLocatorUnitTests { @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 + @Test(expected = IllegalArgumentException.class) 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"); + try { + GemfireBeanFactoryLocator.resolveBeanFactory("UnknownKey"); + } + catch (IllegalArgumentException expected) { - GemfireBeanFactoryLocator.resolveBeanFactory("UnknownKey"); + assertThat(expected).hasMessage("BeanFactory for key [UnknownKey] was not found"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @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); @@ -169,6 +180,7 @@ public class GemfireBeanFactoryLocatorUnitTests { @Test public void resolveSingleBeanFactoryWhenMultipleIdenticalBeanFactoriesAreRegisteredReturnsSingleBeanFactory() { + GemfireBeanFactoryLocator.BEAN_FACTORIES.put("refOne", mockBeanFactory); GemfireBeanFactoryLocator.BEAN_FACTORIES.put("refTwo", mockBeanFactory); @@ -176,23 +188,31 @@ public class GemfireBeanFactoryLocatorUnitTests { assertThat(GemfireBeanFactoryLocator.resolveSingleBeanFactory()).isSameAs(mockBeanFactory); } - @Test + @Test(expected = IllegalStateException.class) 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"); + try { + GemfireBeanFactoryLocator.resolveSingleBeanFactory(); + } + catch (IllegalStateException expected) { - GemfireBeanFactoryLocator.resolveSingleBeanFactory(); + assertThat(expected) + .hasMessage("BeanFactory key must be specified when more than one BeanFactory [refOne, refTwo] is registered"); + + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void registerAliasesIsSuccessful() { + Set aliases = asSet("aliasOne", "aliasTwo", "aliasThree"); GemfireBeanFactoryLocator.registerAliases(aliases, mockBeanFactory); @@ -208,6 +228,7 @@ public class GemfireBeanFactoryLocatorUnitTests { @Test public void registerAliasesWithEmptyAliasesAndNonNullBeanFactoryDoesNothing() { + GemfireBeanFactoryLocator.registerAliases(Collections.emptySet(), mockBeanFactory); assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.isEmpty()).isTrue(); @@ -215,22 +236,30 @@ public class GemfireBeanFactoryLocatorUnitTests { @Test public void registerAliasesWithEmptyAliasesAndNullBeanFactoryDoesNothing() { + GemfireBeanFactoryLocator.registerAliases(Collections.emptySet(), null); assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.isEmpty()).isTrue(); } - @Test + @Test(expected = IllegalArgumentException.class) 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); + try { + GemfireBeanFactoryLocator.registerAliases(asSet("aliasOne", "aliasTwo"), null); + } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("BeanFactory must not be null when aliases are specified"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void registerAliasesWithNullAliasesHandlesNullAndDoesNothing() { + GemfireBeanFactoryLocator.registerAliases(null, null); assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.isEmpty()).isTrue(); @@ -238,6 +267,7 @@ public class GemfireBeanFactoryLocatorUnitTests { @Test public void registerAliasesWhenIdenticalBeanFactoryReferencesAlreadyExistIsSuccessful() { + GemfireBeanFactoryLocator.BEAN_FACTORIES.put("aliasTwo", mockBeanFactory); assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.size()).isEqualTo(1); @@ -250,22 +280,29 @@ public class GemfireBeanFactoryLocatorUnitTests { assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.get("aliasTwo")).isSameAs(mockBeanFactory); } - @Test + @Test(expected = IllegalArgumentException.class) 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]"); + try { + GemfireBeanFactoryLocator.registerAliases(asSet("aliasOne", "aliasTwo"), mock(BeanFactory.class)); + } + catch (IllegalArgumentException expected) { - GemfireBeanFactoryLocator.registerAliases(asSet("aliasOne", "aliasTwo"), mock(BeanFactory.class)); + assertThat(expected).hasMessage("BeanFactory reference already exists for key [aliasTwo]"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void unregisterAliasesRemovesAll() { + GemfireBeanFactoryLocator.BEAN_FACTORIES.put("aliasOne", mockBeanFactory); GemfireBeanFactoryLocator.BEAN_FACTORIES.put("aliasTwo", mockBeanFactory); @@ -278,6 +315,7 @@ public class GemfireBeanFactoryLocatorUnitTests { @Test public void unregisterAliasesRemovesPartial() { + GemfireBeanFactoryLocator.BEAN_FACTORIES.put("aliasOne", mockBeanFactory); GemfireBeanFactoryLocator.BEAN_FACTORIES.put("aliasTwo", mockBeanFactory); @@ -292,6 +330,7 @@ public class GemfireBeanFactoryLocatorUnitTests { @Test public void unregisterAliasesRemovesNone() { + GemfireBeanFactoryLocator.BEAN_FACTORIES.put("aliasOne", mockBeanFactory); GemfireBeanFactoryLocator.BEAN_FACTORIES.put("aliasTwo", mockBeanFactory); @@ -306,6 +345,7 @@ public class GemfireBeanFactoryLocatorUnitTests { @Test public void afterPropertiesSetResolvesAndInitializesBeanNamesWithAliasesThenRegisterAliases() { + when(mockBeanFactory.getAliases(eq("AssociatedBeanName"))).thenReturn(new String[] { "aliasOne", "aliasTwo" }); GemfireBeanFactoryLocator beanFactoryLocator = newBeanFactoryLocator(mockBeanFactory, "AssociatedBeanName"); @@ -330,6 +370,7 @@ public class GemfireBeanFactoryLocatorUnitTests { @Test public void afterPropertiesSetUnableToResolveInitializeAndRegisterAliasesWithNullBeanFactory() { + GemfireBeanFactoryLocator beanFactoryLocator = newBeanFactoryLocator(null, "AssociatedBeanName"); assertThat(beanFactoryLocator).isNotNull(); @@ -342,6 +383,7 @@ public class GemfireBeanFactoryLocatorUnitTests { @Test public void destroyUnregistersOwningAliases() { + BeanFactory mockBeanFactoryTwo = mock(BeanFactory.class, "MockBeanFactoryTwo"); when(mockBeanFactory.getAliases(eq("AssociatedBeanName"))).thenReturn(new String[] { "aliasOne", "aliasTwo" }); @@ -372,20 +414,27 @@ public class GemfireBeanFactoryLocatorUnitTests { assertThat(GemfireBeanFactoryLocator.BEAN_FACTORIES.keySet()).containsAll(asSet("refOne", "refTwo")); verify(mockBeanFactory, times(1)).getAliases(eq("AssociatedBeanName")); - verifyZeroInteractions(mockBeanFactoryTwo); + verifyNoMoreInteractions(mockBeanFactoryTwo); } - @Test + @Test(expected = IllegalStateException.class) public void useBeanFactoryWhenNoBeanFactoriesAreRegisteredThrowsIllegalStateException() { - exception.expect(IllegalStateException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage(UNINITIALIZED_BEAN_FACTORY_REFERENCE_MESSAGE); - newBeanFactoryLocator().useBeanFactory(); + try { + newBeanFactoryLocator().useBeanFactory(); + } + catch (IllegalStateException expected) { + + assertThat(expected).hasMessage(UNINITIALIZED_BEAN_FACTORY_REFERENCE_MESSAGE); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void useBeanFactoryWhenSingleBeanFactoryIsRegisteredReturnsSingleBeanFactory() { + GemfireBeanFactoryLocator.BEAN_FACTORIES.put("refOne", mockBeanFactory); GemfireBeanFactoryLocator.BEAN_FACTORIES.put("refTwo", mockBeanFactory); @@ -394,23 +443,31 @@ public class GemfireBeanFactoryLocatorUnitTests { assertThat(newBeanFactoryLocator().useBeanFactory()).isSameAs(mockBeanFactory); } - @Test + @Test(expected = IllegalStateException.class) 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"); + try { + newBeanFactoryLocator().useBeanFactory(); + } + catch (IllegalStateException expected) { - newBeanFactoryLocator().useBeanFactory(); + assertThat(expected) + .hasMessage("BeanFactory key must be specified when more than one BeanFactory [refOne, refTwo] is registered"); + + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void useBeanFactoryWhenMultipleBeanFactoriesAreRegisteredWithConfiguredKeyReturnsBeanFactory() { + BeanFactory mockBeanFactoryTwo = mock(BeanFactory.class, "MockBeanFactoryTwo"); GemfireBeanFactoryLocator.BEAN_FACTORIES.put("refOne", mockBeanFactory); @@ -423,6 +480,7 @@ public class GemfireBeanFactoryLocatorUnitTests { @Test public void useBeanFactoryWithKeyReturnsSpecificBeanFactory() { + GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyOne", mockBeanFactory); GemfireBeanFactoryLocator.BEAN_FACTORIES.put("keyTwo", mock(BeanFactory.class, "MockBeanFactoryTwo")); @@ -430,22 +488,29 @@ public class GemfireBeanFactoryLocatorUnitTests { assertThat(newBeanFactoryLocator().useBeanFactory("keyOne")).isSameAs(mockBeanFactory); } - @Test + @Test(expected = IllegalArgumentException.class) 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"); + try { + newBeanFactoryLocator().useBeanFactory("UnknownKey"); + } + catch (IllegalArgumentException expected) { - newBeanFactoryLocator().useBeanFactory("UnknownKey"); + assertThat(expected).hasMessage("BeanFactory for key [UnknownKey] was not found"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void setAndGetBeanFactory() { + GemfireBeanFactoryLocator beanFactoryLocator = newBeanFactoryLocator(); assertThat(beanFactoryLocator).isNotNull(); @@ -459,11 +524,12 @@ public class GemfireBeanFactoryLocatorUnitTests { assertThat(beanFactoryLocator.getBeanFactory()).isNull(); - verifyZeroInteractions(mockBeanFactory); + verifyNoInteractions(mockBeanFactory); } @Test public void setAndGetAssociatedBeanName() { + GemfireBeanFactoryLocator beanFactoryLocator = newBeanFactoryLocator(null, "AssociatedBeanName"); assertThat(beanFactoryLocator).isNotNull(); @@ -486,6 +552,7 @@ public class GemfireBeanFactoryLocatorUnitTests { @Test public void withBeanNameIsSuccessful() { + GemfireBeanFactoryLocator beanFactoryLocator = newBeanFactoryLocator(); assertThat(beanFactoryLocator).isNotNull(); diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/LazyWiringDeclarableSupportUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/LazyWiringDeclarableSupportUnitTests.java index 4ccd7c5e..951ede6a 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/LazyWiringDeclarableSupportUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/LazyWiringDeclarableSupportUnitTests.java @@ -14,17 +14,10 @@ * limitations under the License. * */ - package org.springframework.data.gemfire.support; -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.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -35,9 +28,7 @@ import java.util.Properties; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; @@ -46,7 +37,7 @@ import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.ContextRefreshedEvent; /** - * Unit tests for {@link LazyWiringDeclarableSupport}. + * Unit Tests for {@link LazyWiringDeclarableSupport}. * * @author John Blum * @see org.junit.Rule @@ -59,25 +50,29 @@ import org.springframework.context.event.ContextRefreshedEvent; */ public class LazyWiringDeclarableSupportUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - 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))); + + assertThat(parameters).isNotNull(); + assertThat(parameters.containsKey(expectedKey)).isTrue(); + assertThat(parameters.getProperty(expectedKey)).isEqualTo(expectedValue); } private static Properties createParameters(String parameter, String value) { + Properties parameters = new Properties(); + parameters.setProperty(parameter, value); + return parameters; } @Test public void assertInitialized() { + LazyWiringDeclarableSupport declarable = new TestLazyWiringDeclarableSupport() { - @Override protected boolean isInitialized() { + + @Override + protected boolean isInitialized() { return true; } }; @@ -90,23 +85,30 @@ public class LazyWiringDeclarableSupportUnitTests { } } - @Test + @Test(expected = IllegalStateException.class) public void assertInitializedWhenUninitialized() { + LazyWiringDeclarableSupport declarable = new TestLazyWiringDeclarableSupport() { - @Override protected boolean isInitialized() { + + @Override + protected boolean isInitialized() { return false; } }; try { - 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(); } + catch (IllegalStateException expected) { + + assertThat(expected) + .hasMessage("This Declarable object [%s] has not been properly configured and initialized", + declarable.getClass().getName()); + + assertThat(expected).hasNoCause(); + + throw expected; + } finally { SpringContextBootstrappingInitializer.unregister(declarable); } @@ -114,6 +116,7 @@ public class LazyWiringDeclarableSupportUnitTests { @Test public void assertUninitialized() { + LazyWiringDeclarableSupport declarable = new TestLazyWiringDeclarableSupport(); try { @@ -124,9 +127,11 @@ public class LazyWiringDeclarableSupportUnitTests { } } - @Test + @Test(expected = IllegalStateException.class) public void assertUninitializedWhenInitialized() { + LazyWiringDeclarableSupport declarable = new TestLazyWiringDeclarableSupport() { + @Override protected boolean isInitialized() { return true; @@ -134,14 +139,18 @@ public class LazyWiringDeclarableSupportUnitTests { }; try { - 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(); } + catch (IllegalStateException expected) { + + assertThat(expected) + .hasMessage("This Declarable object [%s] has already been configured and initialized", + declarable.getClass().getName()); + + assertThat(expected).hasNoCause(); + + throw expected; + } finally { SpringContextBootstrappingInitializer.unregister(declarable); } @@ -149,10 +158,11 @@ public class LazyWiringDeclarableSupportUnitTests { @Test public void init() { + LazyWiringDeclarableSupport declarable = new TestLazyWiringDeclarableSupport(); try { - assertThat(declarable.isInitialized(), is(false)); + assertThat(declarable.isInitialized()).isFalse(); declarable.init(createParameters("param", "value")); @@ -161,7 +171,7 @@ public class LazyWiringDeclarableSupportUnitTests { declarable.init(createParameters("newParam", "newValue")); assertParameters(declarable.nullSafeGetParameters(), "newParam", "newValue"); - assertThat(declarable.isInitialized(), is(false)); + assertThat(declarable.isInitialized()).isFalse(); } finally { SpringContextBootstrappingInitializer.unregister(declarable); @@ -170,30 +180,37 @@ public class LazyWiringDeclarableSupportUnitTests { @Test public void isInitialized() { + LazyWiringDeclarableSupport declarable = new TestLazyWiringDeclarableSupport() { - @Override protected boolean isInitialized() { + + @Override + protected boolean isInitialized() { return true; } }; - assertThat(declarable.isInitialized(), is(true)); - assertThat(declarable.isNotInitialized(), is(false)); + assertThat(declarable.isInitialized()).isTrue(); + assertThat(declarable.isNotInitialized()).isFalse(); } @Test public void isUninitialized() { + LazyWiringDeclarableSupport declarable = new TestLazyWiringDeclarableSupport() { - @Override protected boolean isInitialized() { + + @Override + protected boolean isInitialized() { return false; } }; - assertThat(declarable.isInitialized(), is(false)); - assertThat(declarable.isNotInitialized(), is(true)); + assertThat(declarable.isInitialized()).isFalse(); + assertThat(declarable.isNotInitialized()).isTrue(); } @Test public void nullSafeGetParametersWithNullReference() { + LazyWiringDeclarableSupport declarable = new TestLazyWiringDeclarableSupport(); try { @@ -201,8 +218,8 @@ public class LazyWiringDeclarableSupportUnitTests { Properties parameters = declarable.nullSafeGetParameters(); - assertThat(parameters, is(notNullValue())); - assertThat(parameters.isEmpty(), is(true)); + assertThat(parameters).isNotNull(); + assertThat(parameters.isEmpty()).isTrue(); } finally { SpringContextBootstrappingInitializer.unregister(declarable); @@ -211,6 +228,7 @@ public class LazyWiringDeclarableSupportUnitTests { @Test public void onApplicationEvent() { + ConfigurableApplicationContext mockApplicationContext = mock(ConfigurableApplicationContext.class); ConfigurableListableBeanFactory mockBeanFactory = mock(ConfigurableListableBeanFactory.class); @@ -219,7 +237,9 @@ public class LazyWiringDeclarableSupportUnitTests { final AtomicBoolean doPostInitCalled = new AtomicBoolean(false); TestLazyWiringDeclarableSupport declarable = new TestLazyWiringDeclarableSupport() { - @Override protected void doPostInit(final Properties parameters) { + + @Override + protected void doPostInit(final Properties parameters) { super.doPostInit(parameters); assertInitialized(); LazyWiringDeclarableSupportUnitTests.assertParameters(parameters, "param", "value"); @@ -235,8 +255,8 @@ public class LazyWiringDeclarableSupportUnitTests { declarable.assertBeanFactory(mockBeanFactory); declarable.assertParameters(parameters); - assertThat(declarable.isInitialized(), is(true)); - assertThat(doPostInitCalled.get(), is(true)); + assertThat(declarable.isInitialized()).isTrue(); + assertThat(doPostInitCalled.get()).isTrue(); verify(mockApplicationContext, times(1)).getBeanFactory(); } @@ -245,8 +265,9 @@ public class LazyWiringDeclarableSupportUnitTests { } } - @Test - public void onApplicationEventWithNullApplicationContext() throws Throwable { + @Test(expected = IllegalArgumentException.class) + public void onApplicationEventWithNullApplicationContext() { + LazyWiringDeclarableSupport declarable = new TestLazyWiringDeclarableSupport(); try { @@ -254,14 +275,19 @@ public class LazyWiringDeclarableSupportUnitTests { when(mockContextRefreshedEvent.getApplicationContext()).thenReturn(null); - 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); } + catch (IllegalArgumentException expected) { + + assertThat(expected) + .hasMessage("The Spring ApplicationContext [null] must be an instance of ConfigurableApplicationContext"); + + assertThat(expected).hasNoCause(); + + throw expected; + } catch (Throwable t) { - assertThat(declarable.isInitialized(), is(false)); + assertThat(declarable.isInitialized()).isFalse(); throw t; } finally { @@ -271,6 +297,7 @@ public class LazyWiringDeclarableSupportUnitTests { @Test public void fullLifecycleOnApplicationEventToDestroy() throws Exception { + ConfigurableApplicationContext mockApplicationContext = mock(ConfigurableApplicationContext.class); ConfigurableListableBeanFactory mockBeanFactory = mock(ConfigurableListableBeanFactory.class); @@ -279,7 +306,9 @@ public class LazyWiringDeclarableSupportUnitTests { final AtomicBoolean doPostInitCalled = new AtomicBoolean(false); TestLazyWiringDeclarableSupport declarable = new TestLazyWiringDeclarableSupport() { - @Override protected void doPostInit(final Properties parameters) { + + @Override + protected void doPostInit(final Properties parameters) { super.doPostInit(parameters); assertInitialized(); LazyWiringDeclarableSupportUnitTests.assertParameters(parameters, "param", "value"); @@ -294,29 +323,29 @@ public class LazyWiringDeclarableSupportUnitTests { try { declarable.init(parameters); - assertThat(declarable.isInitialized(), is(false)); - assertThat(declarable.nullSafeGetParameters(), is(sameInstance(parameters))); - assertThat(doPostInitCalled.get(), is(false)); + assertThat(declarable.isInitialized()).isFalse(); + assertThat(declarable.nullSafeGetParameters()).isSameAs(parameters); + assertThat(doPostInitCalled.get()).isFalse(); initializer.onApplicationEvent(new ContextRefreshedEvent(mockApplicationContext)); - assertThat(declarable.isInitialized(), is(true)); - assertThat(doPostInitCalled.get(), is(true)); + assertThat(declarable.isInitialized()).isTrue(); + assertThat(doPostInitCalled.get()).isTrue(); declarable.assertBeanFactory(mockBeanFactory); declarable.assertParameters(parameters); doPostInitCalled.set(false); declarable.destroy(); - assertThat(declarable.isInitialized(), is(false)); - assertThat(declarable.nullSafeGetParameters(), is(not(sameInstance(parameters)))); - assertThat(doPostInitCalled.get(), is(false)); + assertThat(declarable.isInitialized()).isFalse(); + assertThat(declarable.nullSafeGetParameters()).isNotSameAs(parameters); + assertThat(doPostInitCalled.get()).isFalse(); initializer.onApplicationEvent(new ContextRefreshedEvent(mockApplicationContext)); - assertThat(declarable.isInitialized(), is(false)); - assertThat(declarable.nullSafeGetParameters(), is(not(sameInstance(parameters)))); - assertThat(doPostInitCalled.get(), is(false)); + assertThat(declarable.isInitialized()).isFalse(); + assertThat(declarable.nullSafeGetParameters()).isNotSameAs(parameters); + assertThat(doPostInitCalled.get()).isFalse(); verify(mockApplicationContext, times(1)).getBeanFactory(); } @@ -327,6 +356,7 @@ public class LazyWiringDeclarableSupportUnitTests { @Test public void initThenOnApplicationEventThenInitWhenInitialized() { + BeanFactory mockBeanFactory = mock(BeanFactory.class); ConfigurableApplicationContext mockApplicationContext = mock(ConfigurableApplicationContext.class); @@ -344,7 +374,9 @@ public class LazyWiringDeclarableSupportUnitTests { final AtomicReference expectedValue = new AtomicReference<>("testValue"); TestLazyWiringDeclarableSupport declarable = new TestLazyWiringDeclarableSupport() { - @Override protected void doPostInit(final Properties parameters) { + + @Override + protected void doPostInit(final Properties parameters) { super.doPostInit(parameters); assertInitialized(); LazyWiringDeclarableSupportUnitTests.assertParameters(parameters, expectedKey.get(), expectedValue.get()); @@ -357,26 +389,26 @@ public class LazyWiringDeclarableSupportUnitTests { try { locator.afterPropertiesSet(); - assertThat(declarable.isInitialized(), is(false)); - assertThat(declarable.nullSafeGetParameters(), is(not(sameInstance(parameters)))); - assertThat(doPostInitCalled.get(), is(false)); + assertThat(declarable.isInitialized()).isFalse(); + assertThat(declarable.nullSafeGetParameters()).isNotSameAs(parameters); + assertThat(doPostInitCalled.get()).isFalse(); declarable.init(parameters); declarable.assertBeanFactory(mockBeanFactory); declarable.assertParameters(parameters); - assertThat(declarable.isInitialized(), is(true)); - assertThat(declarable.nullSafeGetParameters(), is(sameInstance(parameters))); - assertThat(doPostInitCalled.get(), is(true)); + assertThat(declarable.isInitialized()).isTrue(); + assertThat(declarable.nullSafeGetParameters()).isSameAs(parameters); + assertThat(doPostInitCalled.get()).isTrue(); doPostInitCalled.set(false); declarable.onApplicationEvent(new ContextRefreshedEvent(mockApplicationContext)); declarable.assertBeanFactory(mockConfigurableListableBeanFactory); declarable.assertParameters(parameters); - assertThat(declarable.isInitialized(), is(true)); - assertThat(declarable.nullSafeGetParameters(), is(sameInstance(parameters))); - assertThat(doPostInitCalled.get(), is(true)); + assertThat(declarable.isInitialized()).isTrue(); + assertThat(declarable.nullSafeGetParameters()).isSameAs(parameters); + assertThat(doPostInitCalled.get()).isTrue(); doPostInitCalled.set(false); expectedKey.set("mockKey"); @@ -387,9 +419,9 @@ public class LazyWiringDeclarableSupportUnitTests { declarable.assertBeanFactory(mockBeanFactory); declarable.assertParameters(parameters); - assertThat(declarable.isInitialized(), is(true)); - assertThat(declarable.nullSafeGetParameters(), is(sameInstance(parameters))); - assertThat(doPostInitCalled.get(), is(true)); + assertThat(declarable.isInitialized()).isTrue(); + assertThat(declarable.nullSafeGetParameters()).isSameAs(parameters); + assertThat(doPostInitCalled.get()).isTrue(); verify(mockApplicationContext, times(1)).getBeanFactory(); } @@ -403,12 +435,12 @@ public class LazyWiringDeclarableSupportUnitTests { private BeanFactory actualBeanFactory; private Properties actualParameters; - private void assertBeanFactory(final BeanFactory expectedBeanFactory) { - assertThat(this.actualBeanFactory, is(sameInstance(expectedBeanFactory))); + private void assertBeanFactory(BeanFactory expectedBeanFactory) { + assertThat(this.actualBeanFactory).isSameAs(expectedBeanFactory); } - private void assertParameters(final Properties expectedParameters) { - assertThat(this.actualParameters, is(equalTo(expectedParameters))); + private void assertParameters(Properties expectedParameters) { + assertThat(this.actualParameters).isEqualTo(expectedParameters); } @Override diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/SpringServerLauncherCacheProviderIntegrationTest.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/SpringServerLauncherCacheProviderIntegrationTests.java similarity index 80% rename from spring-data-geode/src/test/java/org/springframework/data/gemfire/support/SpringServerLauncherCacheProviderIntegrationTest.java rename to spring-data-geode/src/test/java/org/springframework/data/gemfire/support/SpringServerLauncherCacheProviderIntegrationTests.java index eac85cfc..3f00fb57 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/SpringServerLauncherCacheProviderIntegrationTest.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/SpringServerLauncherCacheProviderIntegrationTests.java @@ -15,25 +15,21 @@ */ package org.springframework.data.gemfire.support; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.After; +import org.junit.Test; import org.apache.geode.cache.Cache; import org.apache.geode.distributed.AbstractLauncher.Status; import org.apache.geode.distributed.ServerLauncher; import org.apache.geode.distributed.ServerLauncher.ServerState; -import org.junit.After; -import org.junit.Test; - import org.springframework.context.ConfigurableApplicationContext; import org.springframework.data.gemfire.GemfireUtils; /** - * The SpringServerLauncherCacheProviderTest class is a test suite of test cases testing the contract and functionality - * of the {@link SpringServerLauncherCacheProvider} class. + * Integration Tests {@link SpringServerLauncherCacheProvider} class. * * This test class focuses on testing isolated units of functionality in the * {@link org.apache.geode.distributed.ServerLauncherCacheProvider} class directly, mocking any dependencies @@ -42,13 +38,13 @@ import org.springframework.data.gemfire.GemfireUtils; * @author Dan Smith * @author John Blum * @see org.junit.Test + * @see org.apache.geode.cache.Cache + * @see org.apache.geode.distributed.ServerLauncher * @see org.springframework.context.ApplicationContext * @see org.springframework.context.ConfigurableApplicationContext * @see org.springframework.data.gemfire.support.SpringServerLauncherCacheProvider - * @see org.apache.geode.cache.Cache - * @see org.apache.geode.distributed.ServerLauncher */ -public class SpringServerLauncherCacheProviderIntegrationTest { +public class SpringServerLauncherCacheProviderIntegrationTests { @After public void tearDown() { @@ -58,7 +54,7 @@ public class SpringServerLauncherCacheProviderIntegrationTest { GemfireUtils.closeClientCache(); } - String gemfireName() { + private String gemfireName() { return GemfireUtils.GEMFIRE_PREFIX + GemfireUtils.NAME_PROPERTY_NAME; } @@ -77,19 +73,18 @@ public class SpringServerLauncherCacheProviderIntegrationTest { ServerState state = launcher.start(); - assertThat(state.getStatus(), is(equalTo(Status.ONLINE))); + assertThat(state.getStatus()).isEqualTo(Status.ONLINE); ConfigurableApplicationContext applicationContext = SpringContextBootstrappingInitializer.getApplicationContext(); Cache cache = applicationContext.getBean(Cache.class); - assertThat(cache, is(notNullValue())); - assertThat(cache.getResourceManager().getCriticalHeapPercentage(), is(equalTo(55.0f))); + assertThat(cache).isNotNull(); + assertThat(cache.getResourceManager().getCriticalHeapPercentage()).isEqualTo(55.0f); state = launcher.stop(); - assertThat(state.getStatus(), is(equalTo(Status.STOPPED))); + assertThat(state.getStatus()).isEqualTo(Status.STOPPED); } - } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/SpringServerLauncherCacheProviderTest.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/SpringServerLauncherCacheProviderUnitTests.java similarity index 80% rename from spring-data-geode/src/test/java/org/springframework/data/gemfire/support/SpringServerLauncherCacheProviderTest.java rename to spring-data-geode/src/test/java/org/springframework/data/gemfire/support/SpringServerLauncherCacheProviderUnitTests.java index 6c4dde09..a35511aa 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/SpringServerLauncherCacheProviderTest.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/support/SpringServerLauncherCacheProviderUnitTests.java @@ -15,11 +15,8 @@ */ package org.springframework.data.gemfire.support; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.eq; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -27,39 +24,40 @@ import static org.mockito.Mockito.when; import java.util.Properties; -import org.apache.geode.cache.Cache; -import org.apache.geode.distributed.ServerLauncher; - import org.junit.After; import org.junit.Test; +import org.apache.geode.cache.Cache; +import org.apache.geode.distributed.ServerLauncher; +import org.apache.geode.distributed.ServerLauncherCacheProvider; + import org.springframework.context.ConfigurableApplicationContext; import org.springframework.data.gemfire.GemfireUtils; /** - * The SpringServerLauncherCacheProviderTest class is a test suite of test cases testing the contract and functionality - * of the {@link SpringServerLauncherCacheProvider} class. This test class focuses on testing isolated units - * of functionality in the {@link org.apache.geode.distributed.ServerLauncherCacheProvider} class directly, mocking - * any dependencies as appropriate, in order for the class to uphold it's contract. + * Unit Tests testing the contract and functionality of the {@link SpringServerLauncherCacheProvider} class. + * + * This test class focuses on testing isolated units of functionality in the {@link ServerLauncherCacheProvider} class + * directly, mocking any dependencies as appropriate, in order for the class to uphold it's contract. * * @author Dan Smith * @author John Blum * @see org.junit.Test * @see org.mockito.Mockito - * @see org.springframework.context.ApplicationContext - * @see org.springframework.context.ConfigurableApplicationContext - * @see org.springframework.data.gemfire.support.SpringServerLauncherCacheProvider * @see org.apache.geode.cache.Cache * @see org.apache.geode.distributed.ServerLauncher * @see org.apache.geode.distributed.ServerLauncherCacheProvider + * @see org.springframework.context.ApplicationContext + * @see org.springframework.context.ConfigurableApplicationContext + * @see org.springframework.data.gemfire.support.SpringServerLauncherCacheProvider */ -public class SpringServerLauncherCacheProviderTest { +public class SpringServerLauncherCacheProviderUnitTests { - String gemfireName() { + private String gemfireName() { return (GemfireUtils.GEMFIRE_PREFIX + GemfireUtils.NAME_PROPERTY_NAME); } - Properties singletonProperties(String propertyName, String propertyValue) { + private Properties singletonProperties(String propertyName, String propertyValue) { Properties properties = new Properties(); properties.setProperty(propertyName, propertyValue); return properties; @@ -73,6 +71,7 @@ public class SpringServerLauncherCacheProviderTest { @Test public void createsCacheWhenSpringXmlLocationIsSpecified() { + Cache mockCache = mock(Cache.class); ConfigurableApplicationContext mockApplicationContext = mock(ConfigurableApplicationContext.class); ServerLauncher mockServerLauncher = mock(ServerLauncher.class); @@ -87,6 +86,7 @@ public class SpringServerLauncherCacheProviderTest { final SpringContextBootstrappingInitializer initializer = mock(SpringContextBootstrappingInitializer.class); SpringServerLauncherCacheProvider provider = new SpringServerLauncherCacheProvider() { + @Override public SpringContextBootstrappingInitializer newSpringContextBootstrappingInitializer() { return initializer; @@ -96,7 +96,7 @@ public class SpringServerLauncherCacheProviderTest { Properties expectedParameters = singletonProperties( SpringContextBootstrappingInitializer.CONTEXT_CONFIG_LOCATIONS_PARAMETER, "test-context.xml"); - assertThat(provider.createCache(null, mockServerLauncher), is(equalTo(mockCache))); + assertThat(provider.createCache(null, mockServerLauncher)).isEqualTo(mockCache); verify(mockServerLauncher, times(1)).isSpringXmlLocationSpecified(); verify(mockServerLauncher, times(1)).getSpringXmlLocation(); @@ -107,13 +107,13 @@ public class SpringServerLauncherCacheProviderTest { @Test public void doesNothingWhenSpringXmlLocationNotSpecified() { + ServerLauncher launcher = mock(ServerLauncher.class); when(launcher.isSpringXmlLocationSpecified()).thenReturn(false); - assertThat(new SpringServerLauncherCacheProvider().createCache(null, launcher), is(nullValue())); + assertThat(new SpringServerLauncherCacheProvider().createCache(null, launcher)).isNull(); verify(launcher, times(1)).isSpringXmlLocationSpecified(); } - } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/util/PropertiesBuilderTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/util/PropertiesBuilderTests.java index 75acd7cf..c6a92bd2 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/util/PropertiesBuilderTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/util/PropertiesBuilderTests.java @@ -14,15 +14,9 @@ * limitations under the License. * */ - package org.springframework.data.gemfire.util; -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.sameInstance; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -43,53 +37,56 @@ import org.junit.Test; */ public class PropertiesBuilderTests { - protected Properties singletonProperties(String name, String value) { + private Properties singletonProperties(String name, String value) { Properties properties = new Properties(); properties.setProperty(name, value); return properties; } @Test - @SuppressWarnings("unchecked") public void constructDefaultPropertiesBuilder() throws Exception { + PropertiesBuilder builder = new PropertiesBuilder(); Properties properties = builder.build(); - assertThat(properties, is(notNullValue(Properties.class))); - assertThat(builder.getObject(), is(sameInstance(properties))); - assertThat((Class) builder.getObjectType(), is(equalTo(Properties.class))); - assertThat(properties.isEmpty(), is(true)); + assertThat(properties).isNotNull(); + assertThat(builder.getObject()).isSameAs(properties); + assertThat(builder.getObjectType()).isEqualTo(Properties.class); + assertThat(properties.isEmpty()).isTrue(); } @Test public void constructPropertiesBuilderWithDefaultProperties() { + Properties defaults = singletonProperties("one", "1"); PropertiesBuilder builder = new PropertiesBuilder(defaults); Properties properties = builder.build(); - assertThat(properties, is(notNullValue(Properties.class))); - assertThat(properties, is(not(sameInstance(defaults)))); - assertThat(properties, is(equalTo(defaults))); + assertThat(properties).isNotNull(); + assertThat(properties).isNotSameAs(defaults); + assertThat(properties).isEqualTo(defaults); } @Test public void constructPropertiesBuilderWithPropertiesBuilder() { + PropertiesBuilder defaults = new PropertiesBuilder().setProperty("one", "1"); PropertiesBuilder builder = new PropertiesBuilder(defaults); Properties properties = builder.build(); - assertThat(properties, is(notNullValue(Properties.class))); - assertThat(properties.size(), is(equalTo(1))); - assertThat(properties.containsKey("one"), is(true)); - assertThat(properties.getProperty("one"), is(equalTo("1"))); + assertThat(properties).isNotNull(); + assertThat(properties.size()).isEqualTo(1); + assertThat(properties.containsKey("one")).isTrue(); + assertThat(properties.getProperty("one")).isEqualTo("1"); } @Test public void fromInputStreamIsSuccessful() throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); Properties source = singletonProperties("one", "1"); @@ -98,13 +95,14 @@ public class PropertiesBuilderTests { Properties sink = PropertiesBuilder.from(new ByteArrayInputStream(out.toByteArray())).build(); - assertThat(sink, is(notNullValue(Properties.class))); - assertThat(sink, is(not(sameInstance(source)))); - assertThat(sink, is(equalTo(source))); + assertThat(sink).isNotNull(); + assertThat(sink).isNotSameAs(source); + assertThat(sink).isEqualTo(source); } @Test public void fromReaderIsSuccessful() throws IOException { + StringWriter writer = new StringWriter(); Properties source = singletonProperties("one", "1"); @@ -113,13 +111,14 @@ public class PropertiesBuilderTests { Properties sink = PropertiesBuilder.from(new StringReader(writer.toString())).build(); - assertThat(sink, is(notNullValue(Properties.class))); - assertThat(sink, is(not(sameInstance(source)))); - assertThat(sink, is(equalTo(source))); + assertThat(sink).isNotNull(); + assertThat(sink).isNotSameAs(source); + assertThat(sink).isEqualTo(source); } @Test public void fromXmlInputStreamIsSuccessful() throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); Properties source = singletonProperties("one", "1"); @@ -128,37 +127,37 @@ public class PropertiesBuilderTests { Properties sink = PropertiesBuilder.fromXml(new ByteArrayInputStream(out.toByteArray())).build(); - assertThat(sink, is(notNullValue(Properties.class))); - assertThat(sink, is(not(sameInstance(source)))); - assertThat(sink, is(equalTo(source))); + assertThat(sink).isNotNull(); + assertThat(sink).isNotSameAs(source); + assertThat(sink).isEqualTo(source); } @Test - @SuppressWarnings("unchecked") public void propertiesBuilderObjectTypeIsPropertiesClass() { - assertThat((Class) PropertiesBuilder.create().getObjectType(), is(equalTo(Properties.class))); + assertThat(PropertiesBuilder.create().getObjectType()).isEqualTo(Properties.class); } @Test public void propertiesBuilderIsSingletonIsTrue() { - assertThat(new PropertiesBuilder().isSingleton(), is(true)); + assertThat(new PropertiesBuilder().isSingleton()).isTrue(); } @Test public void addPropertiesFromPropertiesIsSuccessful() { + PropertiesBuilder builder = PropertiesBuilder.create() .setProperty("one", "1") .setProperty("two", "@"); Properties sink = builder.build(); - assertThat(sink, is(notNullValue(Properties.class))); - assertThat(sink.size(), is(2)); - assertThat(sink.containsKey("one"), is(true)); - assertThat(sink.containsKey("two"), is(true)); - assertThat(sink.containsKey("three"), is(false)); - assertThat(sink.getProperty("one"), is(equalTo("1"))); - assertThat(sink.getProperty("two"), is(equalTo("@"))); + assertThat(sink).isNotNull(); + assertThat(sink.size()).isEqualTo(2); + assertThat(sink.containsKey("one")).isTrue(); + assertThat(sink.containsKey("two")).isTrue(); + assertThat(sink.containsKey("three")).isFalse(); + assertThat(sink.getProperty("one")).isEqualTo("1"); + assertThat(sink.getProperty("two")).isEqualTo("@"); Properties source = new Properties(); @@ -169,35 +168,37 @@ public class PropertiesBuilderTests { sink = builder.build(); - assertThat(sink, is(notNullValue(Properties.class))); - assertThat(sink.size(), is(equalTo(3))); - assertThat(sink, is(not(sameInstance(source)))); - assertThat(sink.containsKey("one"), is(true)); - assertThat(sink.containsKey("two"), is(true)); - assertThat(sink.containsKey("three"), is(true)); - assertThat(sink.getProperty("one"), is(equalTo("1"))); - assertThat(sink.getProperty("two"), is(equalTo("2"))); - assertThat(sink.getProperty("three"), is(equalTo("3"))); + assertThat(sink).isNotNull(); + assertThat(sink.size()).isEqualTo(3); + assertThat(sink).isNotSameAs(source); + assertThat(sink.containsKey("one")).isTrue(); + assertThat(sink.containsKey("two")).isTrue(); + assertThat(sink.containsKey("three")).isTrue(); + assertThat(sink.getProperty("one")).isEqualTo("1"); + assertThat(sink.getProperty("two")).isEqualTo("2"); + assertThat(sink.getProperty("three")).isEqualTo("3"); } @Test public void addPropertiesFromPropertiesBuilderIsSuccessful() { + PropertiesBuilder source = PropertiesBuilder.create() .setProperty("one", "1") .setProperty("two", "2"); Properties properties = PropertiesBuilder.create().add(source).build(); - assertThat(properties, is(notNullValue(Properties.class))); - assertThat(properties.size(), is(equalTo(2))); - assertThat(properties.containsKey("one"), is(true)); - assertThat(properties.containsKey("two"), is(true)); - assertThat(properties.getProperty("one"), is(equalTo("1"))); - assertThat(properties.getProperty("two"), is(equalTo("2"))); + assertThat(properties).isNotNull(); + assertThat(properties.size()).isEqualTo(2); + assertThat(properties.containsKey("one")).isTrue(); + assertThat(properties.containsKey("two")).isTrue(); + assertThat(properties.getProperty("one")).isEqualTo("1"); + assertThat(properties.getProperty("two")).isEqualTo("2"); } @Test public void setObjectPropertyValuesIsSuccessful() { + Properties properties = PropertiesBuilder.create() .setProperty("boolean", Boolean.TRUE) .setProperty("character", 'A') @@ -206,37 +207,40 @@ public class PropertiesBuilderTests { .setProperty("string", (Object) "test") .build(); - assertThat(properties, is(notNullValue(Properties.class))); - assertThat(properties.size(), is(equalTo(5))); - assertThat(properties.getProperty("boolean"), is(equalTo(Boolean.TRUE.toString()))); - assertThat(properties.getProperty("character"), is(equalTo("A"))); - assertThat(properties.getProperty("integer"), is(equalTo("1"))); - assertThat(properties.getProperty("double"), is(equalTo(String.valueOf(Math.PI)))); - assertThat(properties.getProperty("string"), is(equalTo("test"))); + assertThat(properties).isNotNull(); + assertThat(properties.size()).isEqualTo(5); + assertThat(properties.getProperty("boolean")).isEqualTo(Boolean.TRUE.toString()); + assertThat(properties.getProperty("character")).isEqualTo("A"); + assertThat(properties.getProperty("integer")).isEqualTo("1"); + assertThat(properties.getProperty("double")).isEqualTo(String.valueOf(Math.PI)); + assertThat(properties.getProperty("string")).isEqualTo("test"); } @Test public void setObjectArrayPropertyValueIsSuccessful() { + Properties properties = PropertiesBuilder.create() .setProperty("numbers", new Object[] { "one", "two", "three" }) .build(); - assertThat(properties, is(notNullValue(Properties.class))); - assertThat(properties.size(), is(equalTo(1))); - assertThat(properties.containsKey("numbers"), is(true)); - assertThat(properties.getProperty("numbers"), is(equalTo("one,two,three"))); + assertThat(properties).isNotNull(); + assertThat(properties.size()).isEqualTo(1); + assertThat(properties.containsKey("numbers")).isTrue(); + assertThat(properties.getProperty("numbers")).isEqualTo("one,two,three"); } @Test public void setPropertyIgnoresNullObjectValue() { + Properties properties = PropertiesBuilder.create().setProperty("object", (Object) null).build(); - assertThat(properties, is(notNullValue(Properties.class))); - assertThat(properties.isEmpty(), is(true)); + assertThat(properties).isNotNull(); + assertThat(properties.isEmpty()).isTrue(); } @Test public void setPropertyIgnoresEmptyAndNullLiteralStringValues() { + Properties properties = PropertiesBuilder.create() .setProperty("blank", " ") .setProperty("empty", "") @@ -244,66 +248,72 @@ public class PropertiesBuilderTests { .setProperty("nullWithWhiteSpace", " null ") .build(); - assertThat(properties, is(notNullValue(Properties.class))); - assertThat(properties.isEmpty(), is(true)); + assertThat(properties).isNotNull(); + assertThat(properties.isEmpty()).isTrue(); } @Test public void setPropertyIgnoresEmptyObjectArray() { + Properties properties = PropertiesBuilder.create().setProperty("emptyArray", new Object[0]).build(); - assertThat(properties, is(notNullValue(Properties.class))); - assertThat(properties.isEmpty(), is(true)); + assertThat(properties).isNotNull(); + assertThat(properties.isEmpty()).isTrue(); } @Test public void setPropertyIgnoresNullObjectArray() { + Properties properties = PropertiesBuilder.create().setProperty("nullArray", (Object[]) null).build(); - assertThat(properties, is(notNullValue(Properties.class))); - assertThat(properties.isEmpty(), is(true)); + assertThat(properties).isNotNull(); + assertThat(properties.isEmpty()).isTrue(); } @Test public void setStringPropertyValuesIsSuccessful() { + Properties properties = PropertiesBuilder.create() .setProperty("one", "1") .setProperty("two", "2") .build(); - assertThat(properties, is(notNullValue(Properties.class))); - assertThat(properties.size(), is(equalTo(2))); - assertThat(properties.containsKey("one"), is(true)); - assertThat(properties.containsKey("two"), is(true)); - assertThat(properties.getProperty("one"), is(equalTo("1"))); - assertThat(properties.getProperty("two"), is(equalTo("2"))); + assertThat(properties).isNotNull(); + assertThat(properties.size()).isEqualTo(2); + assertThat(properties.containsKey("one")).isTrue(); + assertThat(properties.containsKey("two")).isTrue(); + assertThat(properties.getProperty("one")).isEqualTo("1"); + assertThat(properties.getProperty("two")).isEqualTo("2"); } @Test public void unsetPropertyIsSuccessful() { + Properties properties = PropertiesBuilder.create().unsetProperty("example").build(); - assertThat(properties, is(notNullValue(Properties.class))); - assertThat(properties.size(), is(equalTo(1))); - assertThat(properties.containsKey("example"), is(true)); - assertThat(properties.getProperty("example"), is(equalTo(""))); + assertThat(properties).isNotNull(); + assertThat(properties.size()).isEqualTo(1); + assertThat(properties.containsKey("example")).isTrue(); + assertThat(properties.getProperty("example")).isEqualTo(""); } @Test public void stringLiteralIsValuable() { - assertThat(PropertiesBuilder.create().isValuable("test"), is(true)); + assertThat(PropertiesBuilder.create().isValuable("test")).isTrue(); } @Test public void nullStringLiteralIsNotValuable() { - assertThat(PropertiesBuilder.create().isValuable("null"), is(false)); - assertThat(PropertiesBuilder.create().isValuable("Null"), is(false)); - assertThat(PropertiesBuilder.create().isValuable("NULL"), is(false)); + + assertThat(PropertiesBuilder.create().isValuable("null")).isFalse(); + assertThat(PropertiesBuilder.create().isValuable("Null")).isFalse(); + assertThat(PropertiesBuilder.create().isValuable("NULL")).isFalse(); } @Test public void emptyStringLiteralIsNotValuable() { - assertThat(PropertiesBuilder.create().isValuable(" "), is(false)); - assertThat(PropertiesBuilder.create().isValuable(""), is(false)); + + assertThat(PropertiesBuilder.create().isValuable(" ")).isFalse(); + assertThat(PropertiesBuilder.create().isValuable("")).isFalse(); } } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/wan/OrderPolicyConverterUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/wan/OrderPolicyConverterUnitTests.java index f1d8a802..70424dcc 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/wan/OrderPolicyConverterUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/wan/OrderPolicyConverterUnitTests.java @@ -13,34 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire.wan; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.apache.geode.cache.wan.GatewaySender; /** - * Unit tests for {@link OrderPolicyConverter}. + * Unit Tests for {@link OrderPolicyConverter}. * * @author John Blum * @see org.junit.Test - * @see org.springframework.data.gemfire.wan.OrderPolicyConverter * @see org.apache.geode.cache.util.Gateway.OrderPolicy + * @see org.springframework.data.gemfire.wan.OrderPolicyConverter * @since 1.7.0 */ public class OrderPolicyConverterUnitTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - private final OrderPolicyConverter converter = new OrderPolicyConverter(); @After @@ -50,18 +42,25 @@ public class OrderPolicyConverterUnitTests { @Test public void convert() { + assertThat(converter.convert("key")).isEqualTo(GatewaySender.OrderPolicy.KEY); assertThat(converter.convert("Partition")).isEqualTo(GatewaySender.OrderPolicy.PARTITION); assertThat(converter.convert("THREAD")).isEqualTo(GatewaySender.OrderPolicy.THREAD); } - @Test + @Test(expected = IllegalArgumentException.class) public void convertIllegalValue() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[process] is not a valid OrderPolicy"); - converter.convert("process"); + try { + converter.convert("process"); + } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[process] is not a valid OrderPolicy"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test @@ -73,12 +72,18 @@ public class OrderPolicyConverterUnitTests { assertThat(converter.getValue()).isEqualTo(GatewaySender.OrderPolicy.THREAD); } - @Test + @Test(expected = IllegalArgumentException.class) public void setAsTextWithIllegalValue() { - exception.expect(IllegalArgumentException.class); - exception.expectCause(is(nullValue(Throwable.class))); - exception.expectMessage("[value] is not a valid OrderPolicy"); - converter.setAsText("value"); + try { + converter.setAsText("value"); + } + catch (IllegalArgumentException expected) { + + assertThat(expected).hasMessage("[value] is not a valid OrderPolicy"); + assertThat(expected).hasNoCause(); + + throw expected; + } } }