From 95ed5b19ea091974079153abf315e35c4bb97c99 Mon Sep 17 00:00:00 2001 From: Deepankar Dixit <90280028+ddixit14@users.noreply.github.com> Date: Thu, 24 Mar 2022 15:16:19 -0400 Subject: [PATCH] Migrating datastore tests to JUnit5 (#1031) * Migrating tests to JUnit5 * fixing code smell issues * Fixing --- .../it/DatastoreIntegrationTests.java | 164 ++- .../it/ParallelDatastoreIntegrationTests.java | 38 +- ...SubclassesDescendantsIntegrationTests.java | 30 +- .../SubclassesReferencesIntegrationTests.java | 30 +- .../query/PartTreeDatastoreQueryTests.java | 1042 ++++++++--------- .../DatastoreRepositoryFactoryTests.java | 36 +- .../SimpleDatastoreRepositoryTests.java | 99 +- 7 files changed, 688 insertions(+), 751 deletions(-) diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/DatastoreIntegrationTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/DatastoreIntegrationTests.java index 7d2b10e9a6..75093eba2a 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/DatastoreIntegrationTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/DatastoreIntegrationTests.java @@ -19,8 +19,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.awaitility.Awaitility.await; -import static org.hamcrest.Matchers.is; -import static org.junit.Assume.assumeThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.any; import static org.mockito.Mockito.reset; @@ -67,13 +65,12 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.dao.EmptyResultDataAccessException; @@ -88,14 +85,15 @@ import org.springframework.data.domain.Sort; import org.springframework.data.repository.query.FluentQuery.FetchableFluentQuery; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.AopTestUtils; import org.springframework.transaction.TransactionSystemException; /** Integration tests for Datastore that use many features. */ -@RunWith(SpringRunner.class) +@EnabledIfSystemProperty(named = "it.datastore", matches = "true") +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = {DatastoreIntegrationTestConfiguration.class}) -public class DatastoreIntegrationTests extends AbstractDatastoreIntegrationTests { +class DatastoreIntegrationTests extends AbstractDatastoreIntegrationTests { // This value is multiplied against recorded actual times needed to wait for eventual // consistency. @@ -132,20 +130,8 @@ public class DatastoreIntegrationTests extends AbstractDatastoreIntegrationTests private final List allTestEntities = Arrays.asList(this.testEntityA, this.testEntityB, this.testEntityC, this.testEntityD); - /** Used to check exception types and messages. */ - @Rule public ExpectedException expectedException = ExpectedException.none(); - - @BeforeClass - public static void checkToRun() { - assumeThat( - "Datastore integration tests are disabled. Please use '-Dit.datastore=true' " - + "to enable them. ", - System.getProperty("it.datastore"), - is("true")); - } - - @After - public void deleteAll() { + @AfterEach + void deleteAll() { this.datastoreTemplate.deleteAll(EmbeddableTreeNode.class); this.datastoreTemplate.deleteAll(AncestorEntity.class); this.datastoreTemplate.deleteAll(AncestorEntity.DescendantEntry.class); @@ -165,8 +151,8 @@ public void deleteAll() { } } - @Before - public void saveEntities() { + @BeforeEach + void saveEntities() { this.testEntityRepository.saveAll(this.allTestEntities); await() .atMost(20, TimeUnit.SECONDS) @@ -174,7 +160,7 @@ public void saveEntities() { } @Test - public void testFindByExampleReference() { + void testFindByExampleReference() { Store store1 = new Store("store1"); Product product1 = new Product(store1); @@ -208,7 +194,7 @@ public void testFindByExampleReference() { } @Test - public void testFindByExample() { + void testFindByExample() { assertThat( this.testEntityRepository.findAll( Example.of(new TestEntity(null, "red", null, Shape.CIRCLE, null)))) @@ -279,7 +265,7 @@ public void testFindByExample() { } @Test - public void testSlice() { + void testSlice() { Slice slice = this.testEntityRepository.findEntitiesWithCustomQuerySlice("red", PageRequest.of(0, 1)); @@ -308,7 +294,7 @@ public void testSlice() { } @Test - public void testNextPageAwareQuery() { + void testNextPageAwareQuery() { DatastorePersistentEntity persistentEntity = this.mappingContext.getPersistentEntity(TestEntity.class); @@ -337,7 +323,7 @@ public void testNextPageAwareQuery() { } @Test - public void testPage() { + void testPage() { Page page = this.testEntityRepository.findEntitiesWithCustomQueryPage("red", PageRequest.of(0, 2)); @@ -361,7 +347,7 @@ public void testPage() { } @Test - public void testProjectionPage() { + void testProjectionPage() { Page page = this.testEntityRepository.getColorsPage( PageRequest.of(0, 3, Sort.by(Sort.Direction.DESC, "color"))); @@ -382,7 +368,7 @@ public void testProjectionPage() { } @Test - public void testSliceSort() { + void testSliceSort() { List results = this.testEntityRepository.findEntitiesWithCustomQuerySort(Sort.by("color")); @@ -393,7 +379,7 @@ public void testSliceSort() { } @Test - public void testSliceSortDesc() { + void testSliceSortDesc() { List results = this.testEntityRepository.findEntitiesWithCustomQuerySort( Sort.by(Sort.Direction.DESC, "color")); @@ -405,7 +391,7 @@ public void testSliceSortDesc() { } @Test - public void testFinds() { + void testFinds() { assertThat(this.testEntityRepository.findByEmbeddedEntityStringField("c")) .containsExactly(this.testEntityC); assertThat(this.testEntityRepository.findByEmbeddedEntityStringField("d")) @@ -463,7 +449,7 @@ public void testFinds() { } @Test - public void testGets() { + void testGets() { assertThat(this.testEntityRepository.getByColor("green")).isNull(); assertThat(this.testEntityRepository.getByColor("blue")).isEqualTo(this.testEntityB); assertThat(this.testEntityRepository.getByColorAndIdGreaterThanEqualOrderById("red", 3L)) @@ -482,19 +468,19 @@ public void testGets() { } @Test - public void testDeleteSomeButNotAll() { + void testDeleteSomeButNotAll() { assertThat(this.testEntityRepository.deleteBySize(1L)).isEqualTo(3); assertThat(this.testEntityRepository.countBySize(1L)).isZero(); } @Test - public void testDeleteAllBySize() { + void testDeleteAllBySize() { this.testEntityRepository.deleteBySizeEquals(1L); assertThat(this.testEntityRepository.countBySize(1L)).isZero(); } @Test - public void testRemoveByColor() { + void testRemoveByColor() { List removedId = this.testEntityRepository.removeByColor("red").stream() .map(TestEntity::getId) @@ -503,7 +489,7 @@ public void testRemoveByColor() { } @Test - public void testUpdateBlobFields() { + void testUpdateBlobFields() { assertThat(this.testEntityRepository.findById(1L)) .isPresent() .get() @@ -519,7 +505,7 @@ public void testUpdateBlobFields() { } @Test - public void testWithCustomQuery() { + void testWithCustomQuery() { assertThat( this.testEntityRepository.findEntitiesWithCustomQueryWithId( 1L, this.datastoreTemplate.createKey(TestEntity.class, 1L))) @@ -543,7 +529,7 @@ public void testWithCustomQuery() { } @Test - public void testCounting() { + void testCounting() { assertThat(this.testEntityRepository.countBySizeAndColor(2, "blue")).isEqualTo(1); assertThat(this.testEntityRepository.getBySize(2L).getColor()).isEqualTo("blue"); assertThat(this.testEntityRepository.countBySizeAndColor(1, "red")).isEqualTo(3); @@ -555,7 +541,7 @@ public void testCounting() { } @Test - public void testClearBlobField() { + void testClearBlobField() { this.testEntityA.setBlobField(null); this.testEntityRepository.save(this.testEntityA); assertThat(this.testEntityRepository.findById(1L)) @@ -565,14 +551,14 @@ public void testClearBlobField() { } @Test - public void testDelete() { + void testDelete() { assertThat(this.testEntityRepository.findAllById(Arrays.asList(1L, 2L))).hasSize(2); this.testEntityRepository.delete(this.testEntityA); assertThat(this.testEntityRepository.findById(1L)).isNotPresent(); } @Test - public void deleteAllByIdTest() { + void deleteAllByIdTest() { assertThat(this.testEntityRepository.findAllById(Arrays.asList(1L, 2L))).hasSize(2); // cast to SimpleDatastoreRepository for method be reachable with Spring Boot 2.4 SimpleDatastoreRepository simpleRepository = @@ -583,7 +569,7 @@ public void deleteAllByIdTest() { } @Test - public void testTransactions() { + void testTransactions() { this.testEntityRepository.deleteAll(); this.transactionalTemplateService.testSaveAndStateConstantInTransaction( @@ -619,7 +605,7 @@ public void testTransactions() { } @Test - public void projectionTest() { + void projectionTest() { reset(datastoreTemplate); assertThat(this.testEntityRepository.findBySize(2L).getColor()).isEqualTo("blue"); @@ -635,7 +621,7 @@ public void projectionTest() { } @Test - public void embeddedEntitiesTest() { + void embeddedEntitiesTest() { EmbeddableTreeNode treeNode10 = new EmbeddableTreeNode(10, null, null); EmbeddableTreeNode treeNode8 = new EmbeddableTreeNode(8, null, null); EmbeddableTreeNode treeNode9 = new EmbeddableTreeNode(9, treeNode8, treeNode10); @@ -649,7 +635,7 @@ public void embeddedEntitiesTest() { } @Test - public void embeddedCollectionTest() { + void embeddedCollectionTest() { EmbeddableTreeNode treeNode10 = new EmbeddableTreeNode(10, null, null); EmbeddableTreeNode treeNode8 = new EmbeddableTreeNode(8, null, null); EmbeddableTreeNode treeNode9 = new EmbeddableTreeNode(9, treeNode8, treeNode10); @@ -666,7 +652,7 @@ public void embeddedCollectionTest() { } @Test - public void ancestorsTest() { + void ancestorsTest() { AncestorEntity.DescendantEntry descendantEntryA = new AncestorEntity.DescendantEntry("a"); AncestorEntity.DescendantEntry descendantEntryB = new AncestorEntity.DescendantEntry("b"); AncestorEntity.DescendantEntry descendantEntryC = new AncestorEntity.DescendantEntry("c"); @@ -701,7 +687,7 @@ public void ancestorsTest() { } @Test - public void referenceTest() { + void referenceTest() { ReferenceEntry parent = saveEntitiesGraph(); ReferenceEntry loadedParent = this.datastoreTemplate.findById(parent.id, ReferenceEntry.class); @@ -724,7 +710,7 @@ public void referenceTest() { } @Test - public void lazyReferenceCollectionTest() { + void lazyReferenceCollectionTest() { ReferenceEntry parent = saveEntitiesGraph(); ReferenceEntry lazyParent = this.datastoreTemplate.findById(parent.id, ReferenceEntry.class); @@ -739,7 +725,7 @@ public void lazyReferenceCollectionTest() { } @Test - public void lazyReferenceTest() throws InterruptedException { + void lazyReferenceTest() throws InterruptedException { LazyEntity lazyParentEntity = new LazyEntity(new LazyEntity(new LazyEntity())); this.datastoreTemplate.save(lazyParentEntity); @@ -754,7 +740,7 @@ public void lazyReferenceTest() throws InterruptedException { } @Test - public void singularLazyPropertyTest() { + void singularLazyPropertyTest() { LazyEntity lazyParentEntity = new LazyEntity(new LazyEntity(new LazyEntity())); this.datastoreTemplate.save(lazyParentEntity); @@ -764,7 +750,7 @@ public void singularLazyPropertyTest() { } @Test - public void lazyReferenceTransactionTest() { + void lazyReferenceTransactionTest() { ReferenceEntry parent = saveEntitiesGraph(); // Exception should be produced if a lazy loaded property accessed outside of the initial @@ -792,7 +778,7 @@ private ReferenceEntry saveEntitiesGraph() { } @Test - public void allocateIdTest() { + void allocateIdTest() { // intentionally null ID value TestEntity testEntity = new TestEntity(null, "red", 1L, Shape.CIRCLE, null); assertThat(testEntity.getId()).isNull(); @@ -802,7 +788,7 @@ public void allocateIdTest() { } @Test - public void mapTest() { + void mapTest() { Map map = new HashMap<>(); map.put("field1", 1L); map.put("field2", 2L); @@ -817,7 +803,7 @@ public void mapTest() { } @Test - public void recursiveSave() { + void recursiveSave() { SubEntity subEntity1 = new SubEntity(); SubEntity subEntity2 = new SubEntity(); SubEntity subEntity3 = new SubEntity(); @@ -870,7 +856,7 @@ public void recursiveSave() { } @Test - public void nullPropertyTest() { + void nullPropertyTest() { SubEntity subEntity1 = new SubEntity(); subEntity1.stringList = Arrays.asList("a", "b", null, "c"); subEntity1.stringProperty = null; @@ -884,7 +870,7 @@ public void nullPropertyTest() { } @Test - public void inheritanceTest() { + void inheritanceTest() { PetOwner petOwner = new PetOwner(); petOwner.pets = Arrays.asList(new Cat("Alice"), new Cat("Bob"), new Pug("Bob"), new Dog("Bob")); @@ -913,7 +899,7 @@ public void inheritanceTest() { } @Test - public void inheritanceTestFindAll() { + void inheritanceTestFindAll() { this.datastoreTemplate.saveAll( Arrays.asList(new Cat("Cat1"), new Dog("Dog1"), new Pug("Dog2"))); @@ -931,7 +917,7 @@ public void inheritanceTestFindAll() { } @Test - public void enumKeys() { + void enumKeys() { Map phone = new HashMap<>(); phone.put(CommunicationChannels.SMS, "123456"); @@ -951,7 +937,7 @@ public void enumKeys() { } @Test - public void mapSubclass() { + void mapSubclass() { CustomMap customMap1 = new CustomMap(); customMap1.put("key1", "val1"); ServiceConfiguration service1 = new ServiceConfiguration("service1", customMap1); @@ -970,26 +956,28 @@ public void mapSubclass() { } @Test - public void readOnlySaveTest() { - this.expectedException.expect(TransactionSystemException.class); - this.expectedException.expectMessage("Cloud Datastore transaction failed to commit."); - this.transactionalTemplateService.writingInReadOnly(); + void readOnlySaveTest() { + + assertThatThrownBy(() -> this.transactionalTemplateService.writingInReadOnly()) + .isInstanceOf(TransactionSystemException.class) + .hasMessageContaining("Cloud Datastore transaction failed to commit."); } @Test - public void readOnlyDeleteTest() { - this.expectedException.expect(TransactionSystemException.class); - this.expectedException.expectMessage("Cloud Datastore transaction failed to commit."); - this.transactionalTemplateService.deleteInReadOnly(); + void readOnlyDeleteTest() { + + assertThatThrownBy(() -> this.transactionalTemplateService.deleteInReadOnly()) + .isInstanceOf(TransactionSystemException.class) + .hasMessageContaining("Cloud Datastore transaction failed to commit."); } @Test - public void readOnlyCountTest() { + void readOnlyCountTest() { assertThat(this.transactionalTemplateService.findByIdInReadOnly(1)).isEqualTo(this.testEntityA); } @Test - public void sameClassDescendantsTest() { + void sameClassDescendantsTest() { Employee entity3 = new Employee(Collections.EMPTY_LIST); Employee entity2 = new Employee(Collections.EMPTY_LIST); Employee entity1 = new Employee(Arrays.asList(entity2, entity3)); @@ -1007,7 +995,7 @@ public void sameClassDescendantsTest() { } @Test - public void testSlicedEntityProjections() { + void testSlicedEntityProjections() { reset(datastoreTemplate); Slice testEntityProjectionSlice = this.testEntityRepository.findBySize(2L, PageRequest.of(0, 1)); @@ -1034,7 +1022,7 @@ public void testSlicedEntityProjections() { } @Test - public void testPageableGqlEntityProjectionsPage() { + void testPageableGqlEntityProjectionsPage() { Page page = this.testEntityRepository.getBySizePage(2L, PageRequest.of(0, 3)); @@ -1047,7 +1035,7 @@ public void testPageableGqlEntityProjectionsPage() { } @Test - public void testPageableGqlEntityProjectionsSlice() { + void testPageableGqlEntityProjectionsSlice() { Slice slice = this.testEntityRepository.getBySizeSlice(2L, PageRequest.of(0, 3)); @@ -1059,8 +1047,9 @@ public void testPageableGqlEntityProjectionsSlice() { assertThat(testEntityProjections.get(0).getColor()).isEqualTo("blue"); } - @Test(timeout = 10000L) - public void testSliceString() { + @Timeout(10000L) + @Test + void testSliceString() { try { Slice slice = this.testEntityRepository.getSliceStringBySize(2L, PageRequest.of(0, 3)); @@ -1080,8 +1069,9 @@ public void testSliceString() { } } - @Test(timeout = 10000L) - public void testUnindex() { + @Timeout(10000L) + @Test + void testUnindex() { SubEntity childSubEntity = new SubEntity(); childSubEntity.stringList = Collections.singletonList(generateString(1600)); childSubEntity.stringProperty = generateString(1600); @@ -1095,7 +1085,7 @@ private String generateString(int length) { } @Test - public void newFieldTest() { + void newFieldTest() { Company company = new Company(1L, Collections.emptyList()); company.name = "name1"; this.datastoreTemplate.save(company); @@ -1107,21 +1097,21 @@ public void newFieldTest() { } @Test - public void returnStreamPartTreeTest() { + void returnStreamPartTreeTest() { this.testEntityRepository.saveAll(this.allTestEntities); Stream resultStream = this.testEntityRepository.findPartTreeStreamByColor("red"); assertThat(resultStream).hasSize(3).contains(testEntityA, testEntityC, testEntityD); } @Test - public void returnStreamGqlTest() { + void returnStreamGqlTest() { this.testEntityRepository.saveAll(this.allTestEntities); Stream resultStream = this.testEntityRepository.findGqlStreamByColor("red"); assertThat(resultStream).hasSize(3).contains(testEntityA, testEntityC, testEntityD); } @Test - public void queryByTimestampTest() { + void queryByTimestampTest() { Timestamp date1 = Timestamp.parseTimestamp("2020-08-04T00:00:00Z"); Timestamp date2 = Timestamp.parseTimestamp("2021-08-04T00:00:00Z"); TestEntity testEntity1 = new TestEntity(1L, "red", 1L, date1); @@ -1142,7 +1132,7 @@ public void queryByTimestampTest() { } @Test - public void testFindByExampleFluent() { + void testFindByExampleFluent() { Example exampleRedCircle = Example.of(new TestEntity(null, "red", null, Shape.CIRCLE, null)); Example exampleRed = Example.of(new TestEntity(null, "red", null, null, null)); diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/ParallelDatastoreIntegrationTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/ParallelDatastoreIntegrationTests.java index f3013d13de..eaf6cb0ce7 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/ParallelDatastoreIntegrationTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/ParallelDatastoreIntegrationTests.java @@ -17,48 +17,38 @@ package com.google.cloud.spring.data.datastore.it; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.junit.Assume.assumeThat; import java.util.function.IntConsumer; import java.util.stream.IntStream; -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; /** Tests performing many operations at the same time using single instances of the repository. */ -@RunWith(SpringRunner.class) +@EnabledIfSystemProperty(named = "it.datastore", matches = "true") +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = {DatastoreIntegrationTestConfiguration.class}) -public class ParallelDatastoreIntegrationTests extends AbstractDatastoreIntegrationTests { +class ParallelDatastoreIntegrationTests extends AbstractDatastoreIntegrationTests { private static final int PARALLEL_OPERATIONS = 10; @Autowired TestEntityRepository testEntityRepository; - @BeforeClass - public static void checkToRun() { - assumeThat( - "Datastore integration tests are disabled. Please use '-Dit.datastore=true' " - + "to enable them. ", - System.getProperty("it.datastore"), - is("true")); - } - - @After - public void deleteAll() { + @AfterEach + void deleteAll() { this.testEntityRepository.deleteAll(); } @Test - public void testParallelOperations() { + void testParallelOperations() { performOperation( - x -> - this.testEntityRepository.save( - new TestEntity((long) x, "color", (long) x, null, null))); + x -> + this.testEntityRepository.save( + new TestEntity((long) x, "color", (long) x, null, null))); waitUntilTrue(() -> this.testEntityRepository.count() == PARALLEL_OPERATIONS - 1); diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/subclasses/descendants/SubclassesDescendantsIntegrationTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/subclasses/descendants/SubclassesDescendantsIntegrationTests.java index fcb417425f..bd86d4922b 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/subclasses/descendants/SubclassesDescendantsIntegrationTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/subclasses/descendants/SubclassesDescendantsIntegrationTests.java @@ -17,8 +17,6 @@ package com.google.cloud.spring.data.datastore.it.subclasses.descendants; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.junit.Assume.assumeThat; import com.google.cloud.datastore.Key; import com.google.cloud.spring.data.datastore.core.DatastoreTemplate; @@ -32,20 +30,21 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.annotation.Id; import org.springframework.stereotype.Repository; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; @Repository interface SubclassesDescendantsEntityArepository extends DatastoreRepository {} -@RunWith(SpringRunner.class) +@EnabledIfSystemProperty(named = "it.datastore", matches = "true") +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = {DatastoreIntegrationTestConfiguration.class}) public class SubclassesDescendantsIntegrationTests extends AbstractDatastoreIntegrationTests { @@ -54,24 +53,15 @@ public class SubclassesDescendantsIntegrationTests extends AbstractDatastoreInte @Autowired private DatastoreTemplate datastoreTemplate; - @BeforeClass - public static void checkToRun() { - assumeThat( - "Datastore integration tests are disabled. Please use '-Dit.datastore=true' " - + "to enable them. ", - System.getProperty("it.datastore"), - is("true")); - } - - @After - public void deleteAll() { + @AfterEach + void deleteAll() { datastoreTemplate.deleteAll(EntityA.class); datastoreTemplate.deleteAll(EntityB.class); datastoreTemplate.deleteAll(EntityC.class); } @Test - public void testEntityCcontainsReferenceToEntityB() { + void testEntityCcontainsReferenceToEntityB() { EntityB entityB1 = new EntityB(); EntityC entityC1 = new EntityC(); entityB1.addEntityC(entityC1); diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/subclasses/references/SubclassesReferencesIntegrationTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/subclasses/references/SubclassesReferencesIntegrationTests.java index bf172343ac..2379d4fb4d 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/subclasses/references/SubclassesReferencesIntegrationTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/it/subclasses/references/SubclassesReferencesIntegrationTests.java @@ -17,8 +17,6 @@ package com.google.cloud.spring.data.datastore.it.subclasses.references; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.junit.Assume.assumeThat; import com.google.cloud.datastore.Key; import com.google.cloud.spring.data.datastore.core.DatastoreTemplate; @@ -29,21 +27,22 @@ import com.google.cloud.spring.data.datastore.it.DatastoreIntegrationTestConfiguration; import com.google.cloud.spring.data.datastore.repository.DatastoreRepository; import java.util.Arrays; -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Reference; import org.springframework.stereotype.Repository; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; @Repository interface SubclassesReferencesEntityArepository extends DatastoreRepository {} -@RunWith(SpringRunner.class) +@EnabledIfSystemProperty(named = "it.datastore", matches = "true") +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = {DatastoreIntegrationTestConfiguration.class}) public class SubclassesReferencesIntegrationTests extends AbstractDatastoreIntegrationTests { @@ -52,24 +51,15 @@ public class SubclassesReferencesIntegrationTests extends AbstractDatastoreInteg @Autowired private DatastoreTemplate datastoreTemplate; - @BeforeClass - public static void checkToRun() { - assumeThat( - "Datastore integration tests are disabled. Please use '-Dit.datastore=true' " - + "to enable them. ", - System.getProperty("it.datastore"), - is("true")); - } - - @After - public void deleteAll() { + @AfterEach + void deleteAll() { datastoreTemplate.deleteAll(EntityA.class); datastoreTemplate.deleteAll(EntityB.class); datastoreTemplate.deleteAll(EntityC.class); } @Test - public void testEntityCcontainsReferenceToEntityB() { + void testEntityCcontainsReferenceToEntityB() { EntityB entityB1 = new EntityB(); EntityC entityC1 = new EntityC(entityB1); entityArepository.saveAll(Arrays.asList(entityB1, entityC1)); diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/query/PartTreeDatastoreQueryTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/query/PartTreeDatastoreQueryTests.java index a9f9aa3955..29d18390b4 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/query/PartTreeDatastoreQueryTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/query/PartTreeDatastoreQueryTests.java @@ -17,6 +17,7 @@ package com.google.cloud.spring.data.datastore.repository.query; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; @@ -57,10 +58,8 @@ import java.util.Optional; import java.util.function.Function; import java.util.stream.Stream; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.data.annotation.Id; import org.springframework.data.domain.Page; @@ -78,19 +77,19 @@ import org.springframework.lang.Nullable; /** Tests for Part-Tree Datastore Query Methods. */ -public class PartTreeDatastoreQueryTests { +class PartTreeDatastoreQueryTests { private static final Object[] EMPTY_PARAMETERS = new Object[0]; private static final DatastoreResultsIterable EMPTY_RESPONSE = - new DatastoreResultsIterable<>(Collections.emptyIterator(), null); + new DatastoreResultsIterable<>(Collections.emptyIterator(), null); static final CompositeFilter FILTER = - CompositeFilter.and( - PropertyFilter.eq("action", "BUY"), - PropertyFilter.eq("ticker", "abcd"), - PropertyFilter.lt("price", 8.88), - PropertyFilter.ge("price", 3.33), - PropertyFilter.isNull("__key__")); + CompositeFilter.and( + PropertyFilter.eq("action", "BUY"), + PropertyFilter.eq("ticker", "abcd"), + PropertyFilter.lt("price", 8.88), + PropertyFilter.ge("price", 3.33), + PropertyFilter.isNull("__key__")); private DatastoreTemplate datastoreTemplate; @@ -104,47 +103,44 @@ public class PartTreeDatastoreQueryTests { private ReadWriteConversions readWriteConversions; - /** used to check exception messages and types. */ - @Rule public ExpectedException expectedException = ExpectedException.none(); - - @Before - public void initMocks() { + @BeforeEach + void initMocks() { this.queryMethod = mock(DatastoreQueryMethod.class); when(this.queryMethod.getReturnedObjectType()).thenReturn((Class) Trade.class); this.datastoreTemplate = mock(DatastoreTemplate.class); this.datastoreMappingContext = new DatastoreMappingContext(); this.datastoreEntityConverter = mock(DatastoreEntityConverter.class); this.readWriteConversions = - new TwoStepsConversions( - new DatastoreCustomConversions(), null, this.datastoreMappingContext); + new TwoStepsConversions( + new DatastoreCustomConversions(), null, this.datastoreMappingContext); when(this.datastoreTemplate.getDatastoreEntityConverter()) - .thenReturn(this.datastoreEntityConverter); + .thenReturn(this.datastoreEntityConverter); when(this.datastoreEntityConverter.getConversions()).thenReturn(this.readWriteConversions); } private PartTreeDatastoreQuery createQuery( - boolean isPageQuery, boolean isSliceQuery, ProjectionInformation projectionInformation) { + boolean isPageQuery, boolean isSliceQuery, ProjectionInformation projectionInformation) { ProjectionFactory projectionFactory = mock(ProjectionFactory.class); doReturn(projectionInformation != null ? projectionInformation : getProjectionInformationMock()) - .when(projectionFactory) - .getProjectionInformation(any()); + .when(projectionFactory) + .getProjectionInformation(any()); PartTreeDatastoreQuery tradePartTreeDatastoreQuery = - new PartTreeDatastoreQuery<>( - this.queryMethod, - this.datastoreTemplate, - this.datastoreMappingContext, - Trade.class, - projectionFactory); + new PartTreeDatastoreQuery<>( + this.queryMethod, + this.datastoreTemplate, + this.datastoreMappingContext, + Trade.class, + projectionFactory); PartTreeDatastoreQuery spy = spy(tradePartTreeDatastoreQuery); doReturn(isPageQuery).when(spy).isPageQuery(); doReturn(isSliceQuery).when(spy).isSliceQuery(); doAnswer(invocation -> invocation.getArguments()[0]) - .when(spy) - .processRawObjectForProjection(any()); + .when(spy) + .processRawObjectForProjection(any()); doAnswer(invocation -> invocation.getArguments()[0]) - .when(spy) - .convertResultCollection(any(), isNotNull()); + .when(spy) + .convertResultCollection(any(), isNotNull()); return spy; } @@ -156,21 +152,21 @@ private ProjectionInformation getProjectionInformationMock() { } @Test - public void compoundNameConventionTest() throws NoSuchMethodException { + void compoundNameConventionTest() throws NoSuchMethodException { queryWithMockResult( - "findTop333ByActionAndSymbolAndPriceLessThan" - + "AndPriceGreaterThanEqual" - + "AndEmbeddedEntityStringFieldEquals" - + "AndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod( - "tradeMethod", - String.class, - String.class, - double.class, - double.class, - String.class)); + "findTop333ByActionAndSymbolAndPriceLessThan" + + "AndPriceGreaterThanEqual" + + "AndEmbeddedEntityStringFieldEquals" + + "AndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod( + "tradeMethod", + String.class, + String.class, + double.class, + double.class, + String.class)); Object[] params = new Object[] { @@ -183,29 +179,29 @@ public void compoundNameConventionTest() throws NoSuchMethodException { }; when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); - - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter( - CompositeFilter.and( - PropertyFilter.eq("action", "BUY"), - PropertyFilter.eq("ticker", "abcd"), - PropertyFilter.lt("price", 8L), - PropertyFilter.ge("price", 3.33), - PropertyFilter.eq("embeddedEntity.stringField", "abc"), - PropertyFilter.isNull("__key__"))) - .setKind("trades") - .setOrderBy(OrderBy.desc("__key__")) - .setLimit(333) - .build(); - - assertThat(statement).isEqualTo(expected); - - return EMPTY_RESPONSE; - }); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); + + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter( + CompositeFilter.and( + PropertyFilter.eq("action", "BUY"), + PropertyFilter.eq("ticker", "abcd"), + PropertyFilter.lt("price", 8L), + PropertyFilter.ge("price", 3.33), + PropertyFilter.eq("embeddedEntity.stringField", "abc"), + PropertyFilter.isNull("__key__"))) + .setKind("trades") + .setOrderBy(OrderBy.desc("__key__")) + .setLimit(333) + .build(); + + assertThat(statement).isEqualTo(expected); + + return EMPTY_RESPONSE; + }); when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class); @@ -214,69 +210,65 @@ public void compoundNameConventionTest() throws NoSuchMethodException { } @Test - public void compoundNameConventionProjectionTest() - throws NoSuchMethodException, IntrospectionException { + void compoundNameConventionProjectionTest() + throws NoSuchMethodException, IntrospectionException { ProjectionInformation projectionInformation = mock(ProjectionInformation.class); doReturn(TradeProjection.class).when(projectionInformation).getType(); doReturn(true).when(projectionInformation).isClosed(); doReturn( Arrays.asList( - new PropertyDescriptor("id", null, null), - new PropertyDescriptor("symbol", null, null))) - .when(projectionInformation) - .getInputProperties(); + new PropertyDescriptor("id", null, null), + new PropertyDescriptor("symbol", null, null))) + .when(projectionInformation) + .getInputProperties(); queryWithMockResult( - "findTop333ByActionAndSymbolAndPriceLessThan" - + "AndPriceGreaterThanEqual" - + "AndEmbeddedEntityStringFieldEquals" - + "AndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod( - "tradeMethodProjection", - String.class, - String.class, - double.class, - double.class, - String.class), - projectionInformation); + "findTop333ByActionAndSymbolAndPriceLessThan" + + "AndPriceGreaterThanEqual" + + "AndEmbeddedEntityStringFieldEquals" + + "AndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod( + "tradeMethodProjection", + String.class, + String.class, + double.class, + double.class, + String.class), + projectionInformation); Object[] params = - new Object[] { - "BUY", - "abcd", - // this int param requires custom conversion - 8, - 3.33, - "abc" - }; + new Object[] {"BUY", "abcd", + // this int param requires custom conversion + 8, 3.33, "abc" + }; when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - StructuredQuery statement = invocation.getArgument(0); - - StructuredQuery expected = - StructuredQuery.newProjectionEntityQueryBuilder() - .addProjection("__key__", "ticker") - .setFilter( - CompositeFilter.and( - PropertyFilter.eq("action", "BUY"), - PropertyFilter.eq("ticker", "abcd"), - PropertyFilter.lt("price", 8L), - PropertyFilter.ge("price", 3.33), - PropertyFilter.eq("embeddedEntity.stringField", "abc"), - PropertyFilter.isNull("__key__"))) - .setKind("trades") - .setOrderBy(OrderBy.desc("__key__")) - .setLimit(333) - .build(); - - assertThat(statement).isEqualTo(expected); - - return EMPTY_RESPONSE; - }); + .thenAnswer( + invocation -> { + StructuredQuery statement = invocation.getArgument(0); + + StructuredQuery expected = + StructuredQuery.newProjectionEntityQueryBuilder() + .addProjection("__key__", "ticker") + .setFilter( + CompositeFilter.and( + PropertyFilter.eq("action", "BUY"), + PropertyFilter.eq("ticker", "abcd"), + PropertyFilter.lt("price", 8L), + PropertyFilter.ge("price", 3.33), + PropertyFilter.eq("embeddedEntity.stringField", "abc"), + PropertyFilter.isNull("__key__"))) + .setKind("trades") + .setOrderBy(OrderBy.desc("__key__")) + .setLimit(333) + .build(); + + assertThat(statement).isEqualTo(expected); + + return EMPTY_RESPONSE; + }); when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class); @@ -285,43 +277,42 @@ public void compoundNameConventionProjectionTest() } @Test - public void ambiguousSortPageableParam() throws NoSuchMethodException { + void ambiguousSortPageableParam() throws NoSuchMethodException { queryWithMockResult( - "findTop333ByActionAndSymbolAndPriceLessThanAndPriceGreater" - + "ThanEqualAndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod( - "tradeMethod", - String.class, - String.class, - double.class, - double.class, - Pageable.class)); + "findTop333ByActionAndSymbolAndPriceLessThanAndPriceGreater" + + "ThanEqualAndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod( + "tradeMethod", + String.class, + String.class, + double.class, + double.class, + Pageable.class)); Object[] params = - new Object[] { - "BUY", "abcd", 8.88, 3.33, PageRequest.of(1, 444, Sort.Direction.ASC, "price") - }; + new Object[] {"BUY", "abcd", 8.88, 3.33, PageRequest.of(1, 444, Sort.Direction.ASC, "price") + }; when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter(FILTER) - .setKind("trades") - .setOffset(444) - .setLimit(444) - .setOrderBy(OrderBy.desc("__key__"), OrderBy.asc("price")) - .build(); + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter(FILTER) + .setKind("trades") + .setOffset(444) + .setLimit(444) + .setOrderBy(OrderBy.desc("__key__"), OrderBy.asc("price")) + .build(); - assertThat(statement).isEqualTo(expected); + assertThat(statement).isEqualTo(expected); - return EMPTY_RESPONSE; - }); + return EMPTY_RESPONSE; + }); when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class); @@ -330,39 +321,39 @@ public void ambiguousSortPageableParam() throws NoSuchMethodException { } @Test - public void nullPageable() throws NoSuchMethodException { + void nullPageable() throws NoSuchMethodException { queryWithMockResult( - "findTop333ByActionAndSymbolAndPriceLessThanAndPriceGreater" - + "ThanEqualAndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod( - "tradeMethod", - String.class, - String.class, - double.class, - double.class, - Pageable.class)); + "findTop333ByActionAndSymbolAndPriceLessThanAndPriceGreater" + + "ThanEqualAndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod( + "tradeMethod", + String.class, + String.class, + double.class, + double.class, + Pageable.class)); Object[] params = new Object[] {"BUY", "abcd", 8.88, 3.33, null}; when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter(FILTER) - .setKind("trades") - .setLimit(333) - .setOrderBy(OrderBy.desc("__key__")) - .build(); + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter(FILTER) + .setKind("trades") + .setLimit(333) + .setOrderBy(OrderBy.desc("__key__")) + .build(); - assertThat(statement).isEqualTo(expected); + assertThat(statement).isEqualTo(expected); - return EMPTY_RESPONSE; - }); + return EMPTY_RESPONSE; + }); when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class); @@ -371,34 +362,34 @@ public void nullPageable() throws NoSuchMethodException { } @Test - public void ambiguousSort() throws NoSuchMethodException { + void ambiguousSort() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" - + "ThanEqualAndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod( - "tradeMethod", String.class, String.class, double.class, double.class, Sort.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + + "ThanEqualAndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod( + "tradeMethod", String.class, String.class, double.class, double.class, Sort.class)); Object[] params = - new Object[] {"BUY", "abcd", 8.88, 3.33, Sort.by(Sort.Direction.ASC, "price")}; + new Object[] {"BUY", "abcd", 8.88, 3.33, Sort.by(Sort.Direction.ASC, "price")}; when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter(FILTER) - .setKind("trades") - .setOrderBy(OrderBy.desc("__key__"), OrderBy.asc("price")) - .build(); + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter(FILTER) + .setKind("trades") + .setOrderBy(OrderBy.desc("__key__"), OrderBy.asc("price")) + .build(); - assertThat(statement).isEqualTo(expected); + assertThat(statement).isEqualTo(expected); - return EMPTY_RESPONSE; - }); + return EMPTY_RESPONSE; + }); when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class); @@ -407,33 +398,33 @@ public void ambiguousSort() throws NoSuchMethodException { } @Test - public void nullSort() throws NoSuchMethodException { + void nullSort() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" - + "ThanEqualAndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod( - "tradeMethod", String.class, String.class, double.class, double.class, Sort.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + + "ThanEqualAndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod( + "tradeMethod", String.class, String.class, double.class, double.class, Sort.class)); Object[] params = new Object[] {"BUY", "abcd", 8.88, 3.33, null}; when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter(FILTER) - .setKind("trades") - .setOrderBy(OrderBy.desc("__key__")) - .build(); + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter(FILTER) + .setKind("trades") + .setOrderBy(OrderBy.desc("__key__")) + .build(); - assertThat(statement).isEqualTo(expected); + assertThat(statement).isEqualTo(expected); - return EMPTY_RESPONSE; - }); + return EMPTY_RESPONSE; + }); when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class); @@ -442,75 +433,76 @@ public void nullSort() throws NoSuchMethodException { } @Test - public void caseInsensitiveSort() throws NoSuchMethodException { - this.expectedException.expectMessage("Datastore doesn't support sorting ignoring case"); + void caseInsensitiveSort() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" - + "ThanEqualAndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod( - "tradeMethod", String.class, String.class, double.class, double.class, Sort.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + + "ThanEqualAndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod( + "tradeMethod", String.class, String.class, double.class, double.class, Sort.class)); Object[] params = - new Object[] {"BUY", "abcd", 8.88, 3.33, Sort.by(Sort.Order.by("price").ignoreCase())}; + new Object[] {"BUY", "abcd", 8.88, 3.33, Sort.by(Sort.Order.by("price").ignoreCase())}; - this.partTreeDatastoreQuery.execute(params); + assertThatThrownBy(() -> this.partTreeDatastoreQuery.execute(params)) + .hasMessage("Datastore doesn't support sorting ignoring case"); } @Test - public void caseNullHandlingSort() throws NoSuchMethodException { - this.expectedException.expectMessage( - "Datastore supports only NullHandling.NATIVE null handling"); + void caseNullHandlingSort() throws NoSuchMethodException { + queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" - + "ThanEqualAndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod( - "tradeMethod", String.class, String.class, double.class, double.class, Sort.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + + "ThanEqualAndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod( + "tradeMethod", String.class, String.class, double.class, double.class, Sort.class)); Object[] params = - new Object[] {"BUY", "abcd", 8.88, 3.33, Sort.by(Sort.Order.by("price").nullsFirst())}; + new Object[] {"BUY", "abcd", 8.88, 3.33, Sort.by(Sort.Order.by("price").nullsFirst())}; - this.partTreeDatastoreQuery.execute(params); + + assertThatThrownBy(() -> this.partTreeDatastoreQuery.execute(params)) + .hasMessage("Datastore supports only NullHandling.NATIVE null handling"); } @Test - public void pageableParam() throws NoSuchMethodException { + void pageableParam() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", - null, - getClass() - .getMethod( - "tradeMethod", - String.class, - String.class, - double.class, - double.class, - Pageable.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", + null, + getClass() + .getMethod( + "tradeMethod", + String.class, + String.class, + double.class, + double.class, + Pageable.class)); Object[] params = - new Object[] {"BUY", "abcd", 8.88, 3.33, PageRequest.of(1, 444, Sort.Direction.DESC, "id")}; + new Object[] {"BUY", "abcd", 8.88, 3.33, PageRequest.of(1, 444, Sort.Direction.DESC, "id")}; when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter(FILTER) - .setKind("trades") - .setOffset(444) - .setOrderBy(OrderBy.desc("__key__")) - .setLimit(444) - .build(); + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter(FILTER) + .setKind("trades") + .setOffset(444) + .setOrderBy(OrderBy.desc("__key__")) + .setLimit(444) + .build(); - assertThat(statement).isEqualTo(expected); + assertThat(statement).isEqualTo(expected); - return EMPTY_RESPONSE; - }); + return EMPTY_RESPONSE; + }); when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class); @@ -519,23 +511,23 @@ public void pageableParam() throws NoSuchMethodException { } @Test - public void pageableQuery() throws NoSuchMethodException { + void pageableQuery() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", - null, - getClass() - .getMethod( - "tradeMethod", - String.class, - String.class, - double.class, - double.class, - Pageable.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", + null, + getClass() + .getMethod( + "tradeMethod", + String.class, + String.class, + double.class, + double.class, + Pageable.class)); this.partTreeDatastoreQuery = createQuery(true, false, null); Object[] params = - new Object[] {"BUY", "abcd", 8.88, 3.33, PageRequest.of(1, 2, Sort.Direction.DESC, "id")}; + new Object[] {"BUY", "abcd", 8.88, 3.33, PageRequest.of(1, 2, Sort.Direction.DESC, "id")}; preparePageResults(2, 2, null, Arrays.asList(3, 4), Arrays.asList(1, 2, 3, 4)); @@ -552,25 +544,25 @@ public void pageableQuery() throws NoSuchMethodException { } @Test - public void pageableQueryNextPage() throws NoSuchMethodException { + void pageableQueryNextPage() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", - null, - getClass() - .getMethod( - "tradeMethod", - String.class, - String.class, - double.class, - double.class, - Pageable.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", + null, + getClass() + .getMethod( + "tradeMethod", + String.class, + String.class, + double.class, + double.class, + Pageable.class)); this.partTreeDatastoreQuery = createQuery(true, false, null); PageRequest pageRequest = PageRequest.of(1, 2, Sort.Direction.DESC, "id"); Cursor cursor = Cursor.copyFrom("abc".getBytes()); Object[] params = - new Object[] {"BUY", "abcd", 8.88, 3.33, DatastorePageable.from(pageRequest, cursor, 99L)}; + new Object[] {"BUY", "abcd", 8.88, 3.33, DatastorePageable.from(pageRequest, cursor, 99L)}; preparePageResults(2, 2, cursor, Arrays.asList(3, 4), Arrays.asList(1, 2, 3, 4)); @@ -585,13 +577,13 @@ public void pageableQueryNextPage() throws NoSuchMethodException { } @Test - public void pageableQueryMissingPageableParamReturnsAllResults() throws NoSuchMethodException { + void pageableQueryMissingPageableParamReturnsAllResults() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" - + "ThanEqualAndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod("tradeMethod", String.class, String.class, double.class, double.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + + "ThanEqualAndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod("tradeMethod", String.class, String.class, double.class, double.class)); this.partTreeDatastoreQuery = createQuery(true, false, null); @@ -611,23 +603,23 @@ public void pageableQueryMissingPageableParamReturnsAllResults() throws NoSuchMe } @Test - public void sliceQueryLast() throws NoSuchMethodException { + void sliceQueryLast() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", - null, - getClass() - .getMethod( - "tradeMethod", - String.class, - String.class, - double.class, - double.class, - Pageable.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", + null, + getClass() + .getMethod( + "tradeMethod", + String.class, + String.class, + double.class, + double.class, + Pageable.class)); this.partTreeDatastoreQuery = createQuery(false, true, null); Object[] params = - new Object[] {"BUY", "abcd", 8.88, 3.33, PageRequest.of(1, 2, Sort.Direction.DESC, "id")}; + new Object[] {"BUY", "abcd", 8.88, 3.33, PageRequest.of(1, 2, Sort.Direction.DESC, "id")}; prepareSliceResults(2, 2, true); @@ -640,13 +632,13 @@ public void sliceQueryLast() throws NoSuchMethodException { } @Test - public void sliceQueryNoPageableParam() throws NoSuchMethodException { + void sliceQueryNoPageableParam() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" - + "ThanEqualAndIdIsNullOrderByIdDesc", - null, - getClass() - .getMethod("tradeMethod", String.class, String.class, double.class, double.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + + "ThanEqualAndIdIsNullOrderByIdDesc", + null, + getClass() + .getMethod("tradeMethod", String.class, String.class, double.class, double.class)); this.partTreeDatastoreQuery = createQuery(false, true, null); @@ -660,27 +652,27 @@ public void sliceQueryNoPageableParam() throws NoSuchMethodException { assertThat(result.hasNext()).isFalse(); verify(this.datastoreTemplate, times(1)) - .queryEntitiesSlice(isA(EntityQuery.class), any(), any()); + .queryEntitiesSlice(isA(EntityQuery.class), any(), any()); } @Test - public void sliceQuery() throws NoSuchMethodException { + void sliceQuery() throws NoSuchMethodException { queryWithMockResult( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", - null, - getClass() - .getMethod( - "tradeMethod", - String.class, - String.class, - double.class, - double.class, - Pageable.class)); + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + "ThanEqualAndIdIsNull", + null, + getClass() + .getMethod( + "tradeMethod", + String.class, + String.class, + double.class, + double.class, + Pageable.class)); this.partTreeDatastoreQuery = createQuery(false, true, null); Object[] params = - new Object[] {"BUY", "abcd", 8.88, 3.33, PageRequest.of(0, 2, Sort.Direction.DESC, "id")}; + new Object[] {"BUY", "abcd", 8.88, 3.33, PageRequest.of(0, 2, Sort.Direction.DESC, "id")}; prepareSliceResults(0, 2, false); @@ -690,80 +682,80 @@ public void sliceQuery() throws NoSuchMethodException { assertThat(result.hasNext()).isFalse(); verify(this.datastoreTemplate, times(1)) - .queryEntitiesSlice(isA(EntityQuery.class), any(), any()); + .queryEntitiesSlice(isA(EntityQuery.class), any(), any()); } private void preparePageResults( - int offset, - Integer limit, - Cursor cursor, - List pageResults, - List fullResults) { + int offset, + Integer limit, + Cursor cursor, + List pageResults, + List fullResults) { when(this.datastoreTemplate.queryKeysOrEntities(isA(EntityQuery.class), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter(FILTER) - .setKind("trades") - .setStartCursor(cursor) - .setOffset(cursor != null ? 0 : offset) - .setOrderBy(OrderBy.desc("__key__")) - .setLimit(limit) - .build(); - - assertThat(statement).isEqualTo(expected); - return new DatastoreResultsIterable( - pageResults.iterator(), Cursor.copyFrom("abc".getBytes())); - }); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter(FILTER) + .setKind("trades") + .setStartCursor(cursor) + .setOffset(cursor != null ? 0 : offset) + .setOrderBy(OrderBy.desc("__key__")) + .setLimit(limit) + .build(); + + assertThat(statement).isEqualTo(expected); + return new DatastoreResultsIterable( + pageResults.iterator(), Cursor.copyFrom("abc".getBytes())); + }); when(this.datastoreTemplate.queryKeysOrEntities(isA(KeyQuery.class), any())) - .thenAnswer( - invocation -> { - KeyQuery statement = invocation.getArgument(0); - KeyQuery expected = - StructuredQuery.newKeyQueryBuilder() - .setFilter(FILTER) - .setKind("trades") - .setOrderBy(OrderBy.desc("__key__")) - .build(); - - assertThat(statement).isEqualTo(expected); - return new DatastoreResultsIterable( - fullResults.iterator(), Cursor.copyFrom("def".getBytes())); - }); + .thenAnswer( + invocation -> { + KeyQuery statement = invocation.getArgument(0); + KeyQuery expected = + StructuredQuery.newKeyQueryBuilder() + .setFilter(FILTER) + .setKind("trades") + .setOrderBy(OrderBy.desc("__key__")) + .build(); + + assertThat(statement).isEqualTo(expected); + return new DatastoreResultsIterable( + fullResults.iterator(), Cursor.copyFrom("def".getBytes())); + }); } private void prepareSliceResults(int offset, Integer queryLimit, Boolean hasNext) { Cursor cursor = Cursor.copyFrom("abc".getBytes()); List datastoreMatchingRecords = Arrays.asList(3, 4, 5); when(this.datastoreTemplate.queryEntitiesSlice(isA(EntityQuery.class), any(), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter(FILTER) - .setKind("trades") - .setOffset(offset) - .setOrderBy(OrderBy.desc("__key__")) - .setLimit(queryLimit) - .build(); - - assertThat(statement).isEqualTo(expected); - return new SliceImpl( - new DatastoreResultsIterable(datastoreMatchingRecords.iterator(), cursor) - .toList(), - Pageable.unpaged(), - hasNext); - }); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter(FILTER) + .setKind("trades") + .setOffset(offset) + .setOrderBy(OrderBy.desc("__key__")) + .setLimit(queryLimit) + .build(); + + assertThat(statement).isEqualTo(expected); + return new SliceImpl( + new DatastoreResultsIterable(datastoreMatchingRecords.iterator(), cursor) + .toList(), + Pageable.unpaged(), + hasNext); + }); } @Test - public void deleteTest() throws NoSuchMethodException { + void deleteTest() throws NoSuchMethodException { queryWithMockResult( - "deleteByAction", null, getClass().getMethod("countByAction", String.class)); + "deleteByAction", null, getClass().getMethod("countByAction", String.class)); this.partTreeDatastoreQuery = createQuery(false, false, null); @@ -783,9 +775,9 @@ public void deleteTest() throws NoSuchMethodException { } @Test - public void deleteReturnCollectionTest() throws NoSuchMethodException { + void deleteReturnCollectionTest() throws NoSuchMethodException { queryWithMockResult( - "deleteByAction", null, getClass().getMethod("countByAction", String.class)); + "deleteByAction", null, getClass().getMethod("countByAction", String.class)); this.partTreeDatastoreQuery = createQuery(false, false, null); @@ -809,263 +801,249 @@ private void prepareDeleteResults(boolean isCollection) { Cursor cursor = Cursor.copyFrom("abc".getBytes()); List datastoreMatchingRecords = Arrays.asList(3, 4, 5); when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - StructuredQuery statement = invocation.getArgument(0); - StructuredQuery.Builder builder = - isCollection - ? StructuredQuery.newEntityQueryBuilder() - : StructuredQuery.newKeyQueryBuilder(); - StructuredQuery expected = - builder.setFilter(PropertyFilter.eq("action", "BUY")).setKind("trades").build(); - - assertThat(statement).isEqualTo(expected); - return new DatastoreResultsIterable(datastoreMatchingRecords.iterator(), cursor); - }); + .thenAnswer( + invocation -> { + StructuredQuery statement = invocation.getArgument(0); + StructuredQuery.Builder builder = + isCollection + ? StructuredQuery.newEntityQueryBuilder() + : StructuredQuery.newKeyQueryBuilder(); + StructuredQuery expected = + builder.setFilter(PropertyFilter.eq("action", "BUY")).setKind("trades").build(); + + assertThat(statement).isEqualTo(expected); + return new DatastoreResultsIterable(datastoreMatchingRecords.iterator(), cursor); + }); } @Test - public void unspecifiedParametersTest() throws NoSuchMethodException { - this.expectedException.expectMessage( - "Too few parameters are provided for query method: " - + "findByActionAndSymbolAndPriceLessThanAndPriceGreaterThanEqualAndIdIsNullOrderByIdDesc"); + void unspecifiedParametersTest() throws NoSuchMethodException { + queryWithMockResult( - "countByTraderIdBetween", null, getClass().getMethod("countByAction", String.class)); + "countByTraderIdBetween", null, getClass().getMethod("countByAction", String.class)); when(this.queryMethod.getName()) - .thenReturn( - "findByActionAndSymbolAndPriceLessThanAndPriceGreater" - + "ThanEqualAndIdIsNullOrderByIdDesc"); + .thenReturn( + "findByActionAndSymbolAndPriceLessThanAndPriceGreater" + + "ThanEqualAndIdIsNullOrderByIdDesc"); this.partTreeDatastoreQuery = createQuery(false, false, null); // There are too few params specified, so the exception will occur. Object[] params = new Object[] {"BUY"}; - this.partTreeDatastoreQuery.execute(params); + assertThatThrownBy(() -> this.partTreeDatastoreQuery.execute(params)) + .hasMessage("Too few parameters are provided for query method: " + + "findByActionAndSymbolAndPriceLessThanAndPriceGreaterThanEqualAndIdIsNullOrderByIdDesc"); } @Test - public void unsupportedParamTypeTest() throws NoSuchMethodException { - this.expectedException.expectMessage( - "Unable to convert class " - + "com.google.cloud.spring.data.datastore.repository.query." - + "PartTreeDatastoreQueryTests$Trade to Datastore supported type."); + void unsupportedParamTypeTest() throws NoSuchMethodException { + queryWithMockResult("findByAction", null, getClass().getMethod("countByPrice", Integer.class)); this.partTreeDatastoreQuery = createQuery(false, false, null); Object[] params = new Object[] {new Trade()}; - this.partTreeDatastoreQuery.execute(params); + assertThatThrownBy(() -> this.partTreeDatastoreQuery.execute(params)) + .hasMessage("Unable to convert class " + + "com.google.cloud.spring.data.datastore.repository.query." + + "PartTreeDatastoreQueryTests$Trade to Datastore supported type."); } @Test - public void unSupportedPredicateTest() throws NoSuchMethodException { - this.expectedException.expectMessage("Unsupported predicate keyword: BETWEEN"); + void unSupportedPredicateTest() throws NoSuchMethodException { queryWithMockResult("countByTraderIdBetween", null, getClass().getMethod("traderAndPrice")); this.partTreeDatastoreQuery = createQuery(false, false, null); - this.partTreeDatastoreQuery.execute(EMPTY_PARAMETERS); + + assertThatThrownBy(() -> this.partTreeDatastoreQuery.execute(EMPTY_PARAMETERS)) + .hasMessageContaining("Unsupported predicate keyword: BETWEEN"); + + } @Test - public void unSupportedOrTest() throws NoSuchMethodException { - this.expectedException.expectMessage( - "Cloud Datastore only supports multiple filters combined with AND"); - - queryWithMockResult("countByTraderIdOrPrice", null, getClass().getMethod("traderAndPrice")); + void unSupportedOrTest() { + //PartTreeDatastoreQuery constructor will fail as part of queryWithMockResult setup + assertThatThrownBy(() -> queryWithMockResult("countByTraderIdOrPrice", null, getClass().getMethod("traderAndPrice"))) + .hasMessage("Cloud Datastore only supports multiple filters combined with AND."); - // this.partTreeDatastoreQuery = createQuery(); - this.partTreeDatastoreQuery.execute(new Object[] {123L, 45L}); } @Test - public void countTest() throws NoSuchMethodException { + void countTest() throws NoSuchMethodException { List results = new ArrayList<>(); results.add(new Trade()); queryWithMockResult( - "countByAction", results, getClass().getMethod("countByAction", String.class)); + "countByAction", results, getClass().getMethod("countByAction", String.class)); PartTreeDatastoreQuery spyQuery = this.partTreeDatastoreQuery; Object[] params = - new Object[] { - "BUY", - }; + new Object[] {"BUY", }; assertThat(spyQuery.execute(params)).isEqualTo(1L); } @Test - public void existShouldBeTrueWhenResultSetIsNotEmpty() throws NoSuchMethodException { + void existShouldBeTrueWhenResultSetIsNotEmpty() throws NoSuchMethodException { List results = new ArrayList<>(); results.add(new Trade()); queryWithMockResult( - "existsByAction", results, getClass().getMethod("countByAction", String.class)); + "existsByAction", results, getClass().getMethod("countByAction", String.class)); PartTreeDatastoreQuery spyQuery = this.partTreeDatastoreQuery; doAnswer(invocation -> invocation.getArgument(0)) - .when(spyQuery) - .processRawObjectForProjection(any()); + .when(spyQuery) + .processRawObjectForProjection(any()); Object[] params = - new Object[] { - "BUY", - }; + new Object[] {"BUY", }; assertThat((boolean) spyQuery.execute(params)).isTrue(); } @Test - public void existShouldBeFalseWhenResultSetIsEmpty() throws NoSuchMethodException { + void existShouldBeFalseWhenResultSetIsEmpty() throws NoSuchMethodException { queryWithMockResult( - "existsByAction", - Collections.emptyList(), - getClass().getMethod("countByAction", String.class)); + "existsByAction", + Collections.emptyList(), + getClass().getMethod("countByAction", String.class)); PartTreeDatastoreQuery spyQuery = this.partTreeDatastoreQuery; doAnswer(invocation -> invocation.getArgument(0)) - .when(spyQuery) - .processRawObjectForProjection(any()); + .when(spyQuery) + .processRawObjectForProjection(any()); Object[] params = - new Object[] { - "BUY", - }; + new Object[] {"BUY", }; assertThat((boolean) spyQuery.execute(params)).isFalse(); } @Test - public void nonCollectionReturnType() throws NoSuchMethodException { + void nonCollectionReturnType() throws NoSuchMethodException { Trade trade = new Trade(); queryWithMockResult( - "findByAction", null, getClass().getMethod("findByAction", String.class), true, null); + "findByAction", null, getClass().getMethod("findByAction", String.class), true, null); Object[] params = - new Object[] { - "BUY", - }; + new Object[] {"BUY", }; when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter(PropertyFilter.eq("action", "BUY")) - .setKind("trades") - .setLimit(1) - .build(); + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter(PropertyFilter.eq("action", "BUY")) + .setKind("trades") + .setLimit(1) + .build(); - assertThat(statement).isEqualTo(expected); + assertThat(statement).isEqualTo(expected); - List results = Collections.singletonList(trade); - return new DatastoreResultsIterable(results.iterator(), null); - }); + List results = Collections.singletonList(trade); + return new DatastoreResultsIterable(results.iterator(), null); + }); assertThat(this.partTreeDatastoreQuery.execute(params)).isEqualTo(trade); } @Test - public void usingIdField() throws NoSuchMethodException { + void usingIdField() throws NoSuchMethodException { Trade trade = new Trade(); queryWithMockResult( - "findByActionAndId", - null, - getClass().getMethod("findByActionAndId", String.class, String.class), - true, - null); + "findByActionAndId", + null, + getClass().getMethod("findByActionAndId", String.class, String.class), + true, + null); Object[] params = new Object[] {"BUY", "id1"}; when(this.datastoreTemplate.createKey("trades", "id1")) - .thenAnswer( - invocation -> - Key.newBuilder("project", invocation.getArgument(0), invocation.getArgument(1)) - .build()); + .thenAnswer( + invocation -> + Key.newBuilder("project", invocation.getArgument(0), invocation.getArgument(1)) + .build()); when(this.datastoreTemplate.queryKeysOrEntities(any(), any())) - .thenAnswer( - invocation -> { - EntityQuery statement = invocation.getArgument(0); - - EntityQuery expected = - StructuredQuery.newEntityQueryBuilder() - .setFilter( - CompositeFilter.and( - PropertyFilter.eq("action", "BUY"), - PropertyFilter.eq( - "__key__", - KeyValue.of(Key.newBuilder("project", "trades", "id1").build())))) - .setKind("trades") - .setLimit(1) - .build(); - - assertThat(statement).isEqualTo(expected); - - List results = Collections.singletonList(trade); - return new DatastoreResultsIterable(results.iterator(), null); - }); + .thenAnswer( + invocation -> { + EntityQuery statement = invocation.getArgument(0); + + EntityQuery expected = + StructuredQuery.newEntityQueryBuilder() + .setFilter( + CompositeFilter.and( + PropertyFilter.eq("action", "BUY"), + PropertyFilter.eq( + "__key__", + KeyValue.of(Key.newBuilder("project", "trades", "id1").build())))) + .setKind("trades") + .setLimit(1) + .build(); + + assertThat(statement).isEqualTo(expected); + + List results = Collections.singletonList(trade); + return new DatastoreResultsIterable(results.iterator(), null); + }); assertThat(this.partTreeDatastoreQuery.execute(params)).isEqualTo(trade); } @Test - public void nonCollectionReturnTypeNoResultsNullable() throws NoSuchMethodException { + void nonCollectionReturnTypeNoResultsNullable() throws NoSuchMethodException { queryWithMockResult( - "findByAction", - Collections.emptyList(), - getClass().getMethod("findByActionNullable", String.class), - true, - null); + "findByAction", + Collections.emptyList(), + getClass().getMethod("findByActionNullable", String.class), + true, + null); Object[] params = - new Object[] { - "BUY", - }; + new Object[] {"BUY", }; assertThat(this.partTreeDatastoreQuery.execute(params)).isNull(); } @Test - public void nonCollectionReturnTypeNoResultsOptional() throws NoSuchMethodException { + void nonCollectionReturnTypeNoResultsOptional() throws NoSuchMethodException { queryWithMockResult( - "findByAction", - Collections.emptyList(), - getClass().getMethod("findByActionOptional", String.class), - true, - null); + "findByAction", + Collections.emptyList(), + getClass().getMethod("findByActionOptional", String.class), + true, + null); Object[] params = - new Object[] { - "BUY", - }; + new Object[] {"BUY", }; assertThat((Optional) this.partTreeDatastoreQuery.execute(params)).isNotPresent(); } @Test - public void streamResultTest() throws NoSuchMethodException { + void streamResultTest() throws NoSuchMethodException { Trade tradeA = new Trade(); tradeA.id = "a"; Trade tradeB = new Trade(); tradeB.id = "b"; queryWithMockResult( - "findStreamByAction", - Arrays.asList(tradeA, tradeB), - getClass().getMethod("findStreamByAction", String.class)); + "findStreamByAction", + Arrays.asList(tradeA, tradeB), + getClass().getMethod("findStreamByAction", String.class)); when(this.queryMethod.isStreamQuery()).thenReturn(true); Object[] params = - new Object[] { - "BUY", - }; + new Object[] {"BUY", }; Object result = this.partTreeDatastoreQuery.execute(params); assertThat(result).isInstanceOf(Stream.class); assertThat((Stream) result).hasSize(2).contains(tradeA, tradeB); } private void queryWithMockResult( - String queryName, List results, Method m, ProjectionInformation projectionInformation) { + String queryName, List results, Method m, ProjectionInformation projectionInformation) { queryWithMockResult(queryName, results, m, false, projectionInformation); } @@ -1074,11 +1052,11 @@ private void queryWithMockResult(String queryName, List results, Method m) { } private void queryWithMockResult( - String queryName, - List results, - Method m, - boolean mockOptionalNullable, - ProjectionInformation projectionInformation) { + String queryName, + List results, + Method m, + boolean mockOptionalNullable, + ProjectionInformation projectionInformation) { when(this.queryMethod.getName()).thenReturn(queryName); doReturn(new DefaultParameters(m)).when(this.queryMethod).getParameters(); if (mockOptionalNullable) { @@ -1086,18 +1064,18 @@ private void queryWithMockResult( doReturn(m.getReturnType()).when(mockMetadata).getReturnedDomainClass(m); doReturn(ClassTypeInformation.fromReturnTypeOf(m)).when(mockMetadata).getReturnType(m); DatastoreQueryMethod datastoreQueryMethod = - new DatastoreQueryMethod(m, mockMetadata, mock(SpelAwareProxyProjectionFactory.class)); + new DatastoreQueryMethod(m, mockMetadata, mock(SpelAwareProxyProjectionFactory.class)); doReturn(datastoreQueryMethod.isOptionalReturnType()) - .when(this.queryMethod) - .isOptionalReturnType(); + .when(this.queryMethod) + .isOptionalReturnType(); doReturn(datastoreQueryMethod.isNullable()).when(this.queryMethod).isNullable(); } this.partTreeDatastoreQuery = createQuery(false, false, projectionInformation); when(this.datastoreTemplate.queryKeysOrEntities(any(), Mockito.>any())) - .thenReturn( - new DatastoreResultsIterable<>( - results != null ? results.iterator() : Collections.emptyIterator(), null)); + .thenReturn( + new DatastoreResultsIterable<>( + results != null ? results.iterator() : Collections.emptyIterator(), null)); } public Trade findByAction(String action) { @@ -1123,12 +1101,12 @@ public Optional findByActionOptional(String action) { } public List tradeMethod( - String action, String symbol, double pless, double pgreater, String embeddedProperty) { + String action, String symbol, double pless, double pgreater, String embeddedProperty) { return null; } public List tradeMethodProjection( - String action, String symbol, double pless, double pgreater, String embeddedProperty) { + String action, String symbol, double pless, double pgreater, String embeddedProperty) { return null; } @@ -1137,12 +1115,12 @@ public List tradeMethod(String action, String symbol, double pless, doubl } public List tradeMethod( - String action, String symbol, double pless, double pgreater, Pageable pageable) { + String action, String symbol, double pless, double pgreater, Pageable pageable) { return null; } public List tradeMethod( - String action, String symbol, double pless, double pgreater, Sort sort) { + String action, String symbol, double pless, double pgreater, Sort sort) { return null; } diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/support/DatastoreRepositoryFactoryTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/support/DatastoreRepositoryFactoryTests.java index ff55280ac0..02cf66b353 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/support/DatastoreRepositoryFactoryTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/support/DatastoreRepositoryFactoryTests.java @@ -17,16 +17,15 @@ package com.google.cloud.spring.data.datastore.repository.support; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import com.google.cloud.spring.data.datastore.core.DatastoreTemplate; import com.google.cloud.spring.data.datastore.core.mapping.DatastoreMappingContext; import com.google.cloud.spring.data.datastore.core.mapping.Entity; import com.google.cloud.spring.data.datastore.core.mapping.Field; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.data.annotation.Id; import org.springframework.data.mapping.MappingException; @@ -34,17 +33,14 @@ import org.springframework.data.repository.core.RepositoryInformation; /** Tests for the Datastore Repository factory. */ -public class DatastoreRepositoryFactoryTests { - - /** used to check exception messages and types. */ - @Rule public ExpectedException expectedException = ExpectedException.none(); +class DatastoreRepositoryFactoryTests { private DatastoreRepositoryFactory datastoreRepositoryFactory; private DatastoreTemplate datastoreTemplate; - @Before - public void setUp() { + @BeforeEach + void setUp() { DatastoreMappingContext datastoreMappingContext = new DatastoreMappingContext(); this.datastoreTemplate = mock(DatastoreTemplate.class); this.datastoreRepositoryFactory = @@ -52,7 +48,7 @@ public void setUp() { } @Test - public void getEntityInformationTest() { + void getEntityInformationTest() { EntityInformation entityInformation = this.datastoreRepositoryFactory.getEntityInformation(TestEntity.class); assertThat(entityInformation.getJavaType()).isEqualTo(TestEntity.class); @@ -64,19 +60,19 @@ public void getEntityInformationTest() { } @Test - public void getEntityInformationNotAvailableTest() { - this.expectedException.expect(MappingException.class); - this.expectedException.expectMessage( - "Could not lookup mapping metadata for domain class: " - + "com.google.cloud.spring.data.datastore.repository.support." - + "DatastoreRepositoryFactoryTests$TestEntity"); + void getEntityInformationNotAvailableTest() { + DatastoreRepositoryFactory factory = new DatastoreRepositoryFactory(mock(DatastoreMappingContext.class), this.datastoreTemplate); - factory.getEntityInformation(TestEntity.class); + + assertThatThrownBy(() -> factory.getEntityInformation(TestEntity.class)) + .isInstanceOf(MappingException.class) + .hasMessage("Could not lookup mapping metadata for domain class: com.google.cloud.spring.data.datastore.repository.support." + + "DatastoreRepositoryFactoryTests$TestEntity"); } @Test - public void getTargetRepositoryTest() { + void getTargetRepositoryTest() { RepositoryInformation repoInfo = mock(RepositoryInformation.class); Mockito.>when(repoInfo.getRepositoryBaseClass()) .thenReturn(SimpleDatastoreRepository.class); @@ -86,7 +82,7 @@ public void getTargetRepositoryTest() { } @Test - public void getRepositoryBaseClassTest() { + void getRepositoryBaseClassTest() { Class baseClass = this.datastoreRepositoryFactory.getRepositoryBaseClass(null); assertThat(baseClass).isEqualTo(SimpleDatastoreRepository.class); } diff --git a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/support/SimpleDatastoreRepositoryTests.java b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/support/SimpleDatastoreRepositoryTests.java index ec4f5ba47f..3cce9a9723 100644 --- a/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/support/SimpleDatastoreRepositoryTests.java +++ b/spring-cloud-gcp-data-datastore/src/test/java/com/google/cloud/spring/data/datastore/repository/support/SimpleDatastoreRepositoryTests.java @@ -17,6 +17,7 @@ package com.google.cloud.spring.data.datastore.repository.support; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; @@ -38,9 +39,7 @@ import java.util.Arrays; import java.util.List; import java.util.function.Function; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import org.springframework.data.domain.Example; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; @@ -49,9 +48,7 @@ import org.springframework.data.repository.query.FluentQuery.FetchableFluentQuery; /** Tests for the default Datastore Repository implementation. */ -public class SimpleDatastoreRepositoryTests { - /** used to check exception messages and types. */ - @Rule public ExpectedException expectedEx = ExpectedException.none(); +class SimpleDatastoreRepositoryTests { private final DatastoreTemplate datastoreTemplate = mock(DatastoreTemplate.class); @@ -62,81 +59,81 @@ public class SimpleDatastoreRepositoryTests { spy(new SimpleDatastoreRepository<>(this.datastoreTemplate, Object.class)); @Test - public void saveTest() { + void saveTest() { Object object = new Object(); this.simpleDatastoreRepository.save(object); verify(this.datastoreTemplate).save(same(object)); } @Test - public void saveAllTest() { + void saveAllTest() { Iterable entities = Arrays.asList(); this.simpleDatastoreRepository.saveAll(entities); verify(this.datastoreTemplate).saveAll(same(entities)); } @Test - public void findByIdTest() { + void findByIdTest() { String id = "key"; this.simpleDatastoreRepository.findById(id); verify(this.datastoreTemplate).findById(id, Object.class); } @Test - public void existsByIdTest() { + void existsByIdTest() { String id = "key"; this.simpleDatastoreRepository.existsById(id); verify(this.datastoreTemplate).existsById(id, Object.class); } @Test - public void findAllTest() { + void findAllTest() { this.simpleDatastoreRepository.findAll(); verify(this.datastoreTemplate).findAll(Object.class); } @Test - public void findAllByIdTest() { + void findAllByIdTest() { List keys = Arrays.asList("1", "2"); this.simpleDatastoreRepository.findAllById(keys); verify(this.datastoreTemplate).findAllById(keys, Object.class); } @Test - public void countTest() { + void countTest() { this.simpleDatastoreRepository.count(); verify(this.datastoreTemplate).count(Object.class); } @Test - public void deleteByIdTest() { + void deleteByIdTest() { String id = "key"; this.simpleDatastoreRepository.deleteById(id); verify(this.datastoreTemplate).deleteById(id, Object.class); } @Test - public void deleteTest() { + void deleteTest() { Object object = new Object(); this.simpleDatastoreRepository.delete(object); verify(this.datastoreTemplate).delete(same(object)); } @Test - public void deleteAllTest() { + void deleteAllTest() { Iterable entities = Arrays.asList(); this.simpleDatastoreRepository.deleteAll(entities); verify(this.datastoreTemplate).deleteAll(same(entities)); } @Test - public void deleteAllClassTest() { + void deleteAllClassTest() { this.simpleDatastoreRepository.deleteAll(); verify(this.datastoreTemplate).deleteAll(Object.class); } @Test - public void runTransactionCallableTest() { + void runTransactionCallableTest() { when(this.datastoreTemplate.performTransaction(any())) .thenAnswer( invocation -> { @@ -151,7 +148,7 @@ public void runTransactionCallableTest() { } @Test - public void findAllPageableAsc() { + void findAllPageableAsc() { this.simpleDatastoreRepository.findAll(PageRequest.of(0, 5, Sort.Direction.ASC, "property1")); verify(this.datastoreTemplate) @@ -166,7 +163,7 @@ public void findAllPageableAsc() { } @Test - public void findAllPageableDesc() { + void findAllPageableDesc() { this.simpleDatastoreRepository.findAll( PageRequest.of(1, 5, Sort.Direction.DESC, "property1", "property2")); verify(this.datastoreTemplate) @@ -185,7 +182,7 @@ public void findAllPageableDesc() { } @Test - public void findAllPageableCursor() { + void findAllPageableCursor() { Cursor cursor = Cursor.copyFrom("abc".getBytes()); Pageable pageable = DatastorePageable.from( @@ -207,14 +204,14 @@ public void findAllPageableCursor() { } @Test - public void findAllByExample() { + void findAllByExample() { Example example = Example.of(new Object()); this.simpleDatastoreRepository.findAll(example); verify(this.datastoreTemplate).queryByExample(same(example), isNull()); } @Test - public void findAllByExampleSort() { + void findAllByExampleSort() { Example example = Example.of(new Object()); Sort sort = Sort.by("id"); this.simpleDatastoreRepository.findAll(example, sort); @@ -224,7 +221,7 @@ public void findAllByExampleSort() { } @Test - public void findAllByExamplePage() { + void findAllByExamplePage() { Example example = Example.of(new Object()); Sort sort = Sort.by("id"); @@ -250,7 +247,7 @@ public void findAllByExamplePage() { } @Test - public void findAllByExamplePageCursor() { + void findAllByExamplePageCursor() { Example example = Example.of(new Object()); Sort sort = Sort.by("id"); Cursor cursor = Cursor.copyFrom("abc".getBytes()); @@ -305,15 +302,18 @@ public void findAllByExamplePageCursor() { } @Test - public void findAllByExamplePageNull() { - this.expectedEx.expect(IllegalArgumentException.class); - this.expectedEx.expectMessage("A non-null pageable is required."); + void findAllByExamplePageNull() { + + Example example = Example.of(new Object()); + + assertThatThrownBy(() -> this.simpleDatastoreRepository.findAll(example, (Pageable) null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A non-null pageable is required."); - this.simpleDatastoreRepository.findAll(Example.of(new Object()), (Pageable) null); } @Test - public void findOneByExample() { + void findOneByExample() { Example example = Example.of(new Object()); doAnswer(invocationOnMock -> new DatastoreResultsIterable(Arrays.asList(1), null)) @@ -327,7 +327,7 @@ public void findOneByExample() { } @Test - public void existsByExampleTrue() { + void existsByExampleTrue() { Example example2 = Example.of(new Object()); doAnswer(invocationOnMock -> Arrays.asList(1)) @@ -343,7 +343,7 @@ public void existsByExampleTrue() { } @Test - public void existsByExampleFalse() { + void existsByExampleFalse() { Example example2 = Example.of(new Object()); doAnswer(invocationOnMock -> Arrays.asList()) @@ -359,7 +359,7 @@ public void existsByExampleFalse() { } @Test - public void countByExample() { + void countByExample() { Example example2 = Example.of(new Object()); doAnswer(invocationOnMock -> Arrays.asList(1, 2, 3)) @@ -372,7 +372,7 @@ public void countByExample() { } @Test - public void countByExampleZero() { + void countByExampleZero() { Example example1 = Example.of(new Object()); doAnswer(invocationOnMock -> new ArrayList<>()) @@ -385,7 +385,7 @@ public void countByExampleZero() { } @Test - public void findAllSortAsc() { + void findAllSortAsc() { this.simpleDatastoreRepository.findAll( Sort.by( new Sort.Order(Sort.Direction.DESC, "property1"), @@ -401,14 +401,14 @@ public void findAllSortAsc() { } @Test - public void deleteAllById() { + void deleteAllById() { List keys = Arrays.asList("1", "2"); this.simpleDatastoreRepository.deleteAllById(keys); verify(this.datastoreTemplate).deleteAllById(keys, Object.class); } @Test - public void findByExampleFluentQueryAll() { + void findByExampleFluentQueryAll() { Example example = Example.of(new Object()); Sort sort = Sort.by("id"); Iterable entities = Arrays.asList(); @@ -422,7 +422,7 @@ public void findByExampleFluentQueryAll() { } @Test - public void findByExampleFluentQueryOneValue() { + void findByExampleFluentQueryOneValue() { Example example = Example.of(new Object()); Iterable entities = Arrays.asList(); doAnswer(invocationOnMock -> new DatastoreResultsIterable(entities, null)) @@ -433,7 +433,7 @@ public void findByExampleFluentQueryOneValue() { } @Test - public void findByExampleFluentQuerySortAndFirstValue() { + void findByExampleFluentQuerySortAndFirstValue() { Example example = Example.of(new Object()); Sort sort = Sort.by("id"); Iterable entities = Arrays.asList(1); @@ -449,7 +449,7 @@ public void findByExampleFluentQuerySortAndFirstValue() { } @Test - public void findByExampleFluentQueryExists() { + void findByExampleFluentQueryExists() { Example example = Example.of(new Object()); doAnswer(invocationOnMock -> Arrays.asList()) .when(this.datastoreTemplate) @@ -461,7 +461,7 @@ public void findByExampleFluentQueryExists() { } @Test - public void findByExampleFluentQueryCount() { + void findByExampleFluentQueryCount() { Example example = Example.of(new Object()); doAnswer(invocationOnMock -> Arrays.asList(1, 2, 3)) .when(this.datastoreTemplate) @@ -472,7 +472,7 @@ public void findByExampleFluentQueryCount() { } @Test - public void findByExampleFluentQueryPage() { + void findByExampleFluentQueryPage() { Example example = Example.of(new Object()); Sort sort = Sort.by("id"); @@ -492,16 +492,19 @@ public void findByExampleFluentQueryPage() { } @Test - public void findByExampleFluentQueryAsUnsupported() { - this.expectedEx.expect(UnsupportedOperationException.class); + void findByExampleFluentQueryAsUnsupported() { + Example example = Example.of(new Object()); - this.simpleDatastoreRepository.findBy(example, q -> q.as(Object.class).all()); + + assertThatThrownBy(() -> this.simpleDatastoreRepository.findBy(example, q -> q.as(Object.class).all())) + .isInstanceOf(UnsupportedOperationException.class); } @Test - public void findByExampleFluentQueryProjectUnsupported() { - this.expectedEx.expect(UnsupportedOperationException.class); + void findByExampleFluentQueryProjectUnsupported() { Example example = Example.of(new Object()); - this.simpleDatastoreRepository.findBy(example, q -> q.project("firstProperty").all()); + + assertThatThrownBy(() -> this.simpleDatastoreRepository.findBy(example, q -> q.project("firstProperty").all())) + .isInstanceOf(UnsupportedOperationException.class); } }