Migrate MongoDB to JUnit 5 (except for ClassRule).

See #583.
This commit is contained in:
Mark Paluch
2021-04-28 15:37:28 +02:00
parent e565f33872
commit ead318ce8d
29 changed files with 366 additions and 455 deletions

View File

@@ -105,11 +105,17 @@ We have separate folders for the samples of individual modules:
## Miscellaneous
* `bom` - Example project how to use the Spring Data release train bom in non-Spring-Boot scenarios.
* `bom` - Example project how to use the Spring Data release train bom in non-Spring-Boot
scenarios.
* `map` - Example project to show how to use `Map`-backed repositories.
* `multi-store` - Example project to use both Spring Data MongoDB and Spring Data JPA in one project.
* `multi-store` - Example project to use both Spring Data MongoDB and Spring Data JPA in
one project.
## Note
* The example projects make use of the [Lombok](https://projectlombok.org/) plugin. To get proper code navigation in your IDE, you must install it separately.
Lombok is available in the IntelliJ plugins repository and as a [download](https://projectlombok.org/download) for Eclipse-based IDEs.
* The example projects make use of the [Lombok](https://projectlombok.org/) plugin. To get
proper code navigation in your IDE, you must install it separately. Lombok is available
in the IntelliJ plugins repository and as
a [download](https://projectlombok.org/download) for Eclipse-based IDEs.
You need Java 16 or newer to run and compile the examples.

View File

@@ -20,13 +20,12 @@ import static org.assertj.core.data.Offset.offset;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Integration tests for {@link OrderRepository}.
@@ -36,9 +35,8 @@ import org.springframework.test.context.junit4.SpringRunner;
* @author Christoph Strobl
* @author Divya Srivastava
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class OrderRepositoryIntegrationTests {
class OrderRepositoryIntegrationTests {
@Autowired OrderRepository repository;
@@ -46,13 +44,13 @@ public class OrderRepositoryIntegrationTests {
private final static LineItem product2 = new LineItem("p2", 0.87, 2);
private final static LineItem product3 = new LineItem("p3", 5.33);
@Before
public void setup() {
@BeforeEach
void setup() {
repository.deleteAll();
}
@Test
public void createsInvoiceViaProgrammaticAggregation() {
void createsInvoiceViaProgrammaticAggregation() {
var order = new Order("c42", new Date()).//
addItem(product1).addItem(product2).addItem(product3);
@@ -68,7 +66,7 @@ public class OrderRepositoryIntegrationTests {
}
@Test
public void createsInvoiceViaDeclarativeAggregation() {
void createsInvoiceViaDeclarativeAggregation() {
var order = new Order("c42", new Date()).//
addItem(product1).addItem(product2).addItem(product3);
@@ -84,7 +82,7 @@ public class OrderRepositoryIntegrationTests {
}
@Test
public void declarativeAggregationWithSort() {
void declarativeAggregationWithSort() {
repository.save(new Order("c42", new Date()).addItem(product1));
repository.save(new Order("c42", new Date()).addItem(product2));
@@ -100,7 +98,7 @@ public class OrderRepositoryIntegrationTests {
}
@Test
public void multiStageDeclarativeAggregation() {
void multiStageDeclarativeAggregation() {
repository.save(new Order("c42", new Date()).addItem(product1));
repository.save(new Order("c42", new Date()).addItem(product2));

View File

@@ -23,9 +23,8 @@ import java.util.List;
import org.assertj.core.util.Files;
import org.bson.Document;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@@ -38,7 +37,6 @@ import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.data.mongodb.core.aggregation.BucketAutoOperation.Granularities;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Examples for Spring Books using the MongoDB Aggregation Framework. Data originates from Google's Book search.
@@ -49,15 +47,14 @@ import org.springframework.test.context.junit4.SpringRunner;
* "https://www.googleapis.com/books/v1/volumes?q=intitle:spring+framework">https://www.googleapis.com/books/v1/volumes?q=intitle:spring+framework</a>
* @see <a href="/books.json>books.json</a>
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBooksIntegrationTests {
class SpringBooksIntegrationTests {
@Autowired MongoOperations operations;
@SuppressWarnings("unchecked")
@Before
public void before() throws Exception {
@BeforeEach
void before() throws Exception {
if (operations.count(new Query(), "books") == 0) {
@@ -74,7 +71,7 @@ public class SpringBooksIntegrationTests {
* Project Book titles.
*/
@Test
public void shouldRetrieveOrderedBookTitles() {
void shouldRetrieveOrderedBookTitles() {
record BookTitle(String title) {
}
@@ -94,7 +91,7 @@ public class SpringBooksIntegrationTests {
* Get number of books that were published by the particular publisher.
*/
@Test
public void shouldRetrieveBooksPerPublisher() {
void shouldRetrieveBooksPerPublisher() {
var aggregation = newAggregation( //
group("volumeInfo.publisher") //
@@ -113,7 +110,7 @@ public class SpringBooksIntegrationTests {
* Get number of books that were published by the particular publisher with their titles.
*/
@Test
public void shouldRetrieveBooksPerPublisherWithTitles() {
void shouldRetrieveBooksPerPublisherWithTitles() {
var aggregation = newAggregation( //
group("volumeInfo.publisher") //
@@ -135,7 +132,7 @@ public class SpringBooksIntegrationTests {
* Filter for Data-related books in their title and output the title and authors.
*/
@Test
public void shouldRetrieveDataRelatedBooks() {
void shouldRetrieveDataRelatedBooks() {
var aggregation = newAggregation( //
match(Criteria.where("volumeInfo.title").regex("data", "i")), //
@@ -156,7 +153,7 @@ public class SpringBooksIntegrationTests {
* Retrieve the number of pages per author (and divide the number of pages by the number of authors).
*/
@Test
public void shouldRetrievePagesPerAuthor() {
void shouldRetrievePagesPerAuthor() {
record PagesPerAuthor(@Id String author, int totalPageCount, int approxWritten) {
}
@@ -187,7 +184,7 @@ public class SpringBooksIntegrationTests {
* Categorize books by their page count into buckets.
*/
@Test
public void shouldCategorizeBooksInBuckets() {
void shouldCategorizeBooksInBuckets() {
var aggregation = newAggregation( //
replaceRoot("volumeInfo"), //
@@ -219,7 +216,7 @@ public class SpringBooksIntegrationTests {
*/
@Test
@SuppressWarnings("unchecked")
public void shouldCategorizeInMultipleFacetsByPriceAndAuthor() {
void shouldCategorizeInMultipleFacetsByPriceAndAuthor() {
var aggregation = newAggregation( //
match(Criteria.where("volumeInfo.authors").exists(true).and("volumeInfo.publisher").exists(true)),
@@ -248,15 +245,15 @@ public class SpringBooksIntegrationTests {
assertThat((List<Object>) uniqueMappedResult.get("authors")).hasSize(8);
}
record BooksPerPublisher(String publisher, int count, List<String> titles) {
private record BooksPerPublisher(String publisher, int count, List<String> titles) {
}
record BookAndAuthors(String title, List<String> authors) {
private record BookAndAuthors(String title, List<String> authors) {
}
record BookFacetPerPage(BookFacetPerPageId id, int count, List<String> titles) {
private record BookFacetPerPage(BookFacetPerPageId id, int count, List<String> titles) {
}
record BookFacetPerPageId(int min, int max) {
private record BookFacetPerPageId(int min, int max) {
}
}

View File

@@ -20,34 +20,32 @@ import static org.assertj.core.api.Assertions.*;
import example.springdata.mongodb.customer.Customer;
import org.bson.Document;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Meta;
import org.springframework.test.context.junit4.SpringRunner;
import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
/**
* @author Christoph Strobl
* @author Oliver Gierke
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class AdvancedIntegrationTests {
@DataMongoTest
class AdvancedIntegrationTests {
@Autowired AdvancedRepository repository;
@Autowired MongoOperations operations;
Customer dave, oliver, carter;
private Customer dave, oliver, carter;
@Before
public void setUp() {
@BeforeEach
void setUp() {
repository.deleteAll();
@@ -63,7 +61,7 @@ public class AdvancedIntegrationTests {
* <strong>NOTE</strong>: Requires MongoDB v. 2.6.4+
*/
@Test
public void findByFirstnameUsingMetaAttributes() {
void findByFirstnameUsingMetaAttributes() {
// execute derived finder method just to get the comment in the profile log
repository.findByFirstname(dave.getFirstname());

View File

@@ -22,30 +22,29 @@ import example.springdata.mongodb.customer.Customer;
import java.util.Map;
import org.bson.Document;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.script.ExecutableMongoScript;
import org.springframework.data.mongodb.core.script.NamedMongoScript;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author Christoph Strobl
* @author Oliver Gierke
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class ServersideScriptTests {
@DataMongoTest
class ServersideScriptTests {
@Autowired AdvancedRepository repository;
@Autowired MongoOperations operations;
@Before
public void setUp() {
@BeforeEach
void setUp() {
if (!operations.collectionExists(Customer.class)) {
operations.createCollection(Customer.class);
@@ -60,7 +59,7 @@ public class ServersideScriptTests {
* Store and call an arbitrary JavaScript function (in this case a simple echo script) via its name.
*/
@Test
public void saveAndCallScriptViaName() {
void saveAndCallScriptViaName() {
operations.scriptOps()
.register(new NamedMongoScript("echoScript", new ExecutableMongoScript("function(x) { return x; }")));
@@ -73,8 +72,8 @@ public class ServersideScriptTests {
* {@link Map#putIfAbsent(Object, Object)}
*/
@Test
@Ignore
public void complexScriptExecutionSimulatingPutIfAbsent() {
@Disabled
void complexScriptExecutionSimulatingPutIfAbsent() {
var ned = new Customer("Ned", "Stark");
ned.setId("ned-stark");

View File

@@ -15,42 +15,38 @@
*/
package example.springdata.mongodb.customer;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.data.Offset.offset;
import java.util.List;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Metrics;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.index.GeospatialIndex;
import org.springframework.data.querydsl.QSort;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Integration test for {@link CustomerRepository}.
*
* @author Oliver Gierke
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerRepositoryIntegrationTest {
@DataMongoTest
class CustomerRepositoryIntegrationTest {
@Autowired CustomerRepository repository;
@Autowired MongoOperations operations;
Customer dave, oliver, carter;
private Customer dave, oliver, carter;
@Before
public void setUp() {
@BeforeEach
void setUp() {
repository.deleteAll();
@@ -63,31 +59,31 @@ public class CustomerRepositoryIntegrationTest {
* Test case to show that automatically generated ids are assigned to the domain objects.
*/
@Test
public void setsIdOnSave() {
void setsIdOnSave() {
var dave = repository.save(new Customer("Dave", "Matthews"));
assertThat(dave.getId(), is(notNullValue()));
assertThat(dave.getId()).isNotNull();
}
/**
* Test case to show the usage of the Querydsl-specific {@link QSort} to define the sort order in a type-safe way.
*/
@Test
public void findCustomersUsingQuerydslSort() {
void findCustomersUsingQuerydslSort() {
var customer = QCustomer.customer;
var result = repository.findByLastname("Matthews", new QSort(customer.firstname.asc()));
assertThat(result, hasSize(2));
assertThat(result.get(0), is(dave));
assertThat(result.get(1), is(oliver));
assertThat(result).hasSize(2);
assertThat(result.get(0)).isEqualTo(dave);
assertThat(result.get(1)).isEqualTo(oliver);
}
/**
* Test case to show the usage of Java {@link Stream}.
*/
@Test
public void findCustomersAsStream() {
void findCustomersAsStream() {
try (var result = repository.findAllByCustomQueryWithStream()) {
result.forEach(System.out::println);
@@ -98,7 +94,7 @@ public class CustomerRepositoryIntegrationTest {
* Test case to show the usage of the geo-spatial APIs to lookup people within a given distance of a reference point.
*/
@Test
public void exposesGeoSpatialFunctionality() {
void exposesGeoSpatialFunctionality() {
var indexDefinition = new GeospatialIndex("address.location");
indexDefinition.getIndexOptions().put("min", -180);
@@ -115,10 +111,10 @@ public class CustomerRepositoryIntegrationTest {
var result = repository.findByAddressLocationNear(referenceLocation, oneKilometer);
assertThat(result.getContent(), hasSize(1));
assertThat(result.getContent()).hasSize(1);
var distanceToFirstStore = result.getContent().get(0).getDistance();
assertThat(distanceToFirstStore.getMetric(), is(Metrics.KILOMETERS));
assertThat(distanceToFirstStore.getValue(), closeTo(0.862, 0.001));
assertThat(distanceToFirstStore.getMetric()).isEqualTo(Metrics.KILOMETERS);
assertThat(distanceToFirstStore.getValue()).isCloseTo(0.862, offset(0.001));
}
}

View File

@@ -17,14 +17,13 @@ package example.springdata.mongodb.immutable;
import static org.assertj.core.api.Assertions.*;
import org.bson.types.ObjectId;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Integration test for {@link ImmutablePerson} showing features around immutable object support.
@@ -32,14 +31,13 @@ import org.springframework.test.context.junit4.SpringRunner;
* @author Mark Paluch
* @author Christoph Strobl
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class ImmutableEntityIntegrationTest {
@DataMongoTest
class ImmutableEntityIntegrationTest {
@Autowired MongoOperations operations;
@Before
public void setUp() {
@BeforeEach
void setUp() {
operations.dropCollection(ImmutablePerson.class);
}
@@ -48,7 +46,7 @@ public class ImmutableEntityIntegrationTest {
* {@link ImmutablePerson#getRandomNumber()} gets set via {@link ApplicationConfiguration#beforeConvertCallback()}.
*/
@Test
public void setsRandomNumberOnSave() {
void setsRandomNumberOnSave() {
var unsaved = new ImmutablePerson();
assertThat(unsaved.getRandomNumber()).isZero();
@@ -64,7 +62,7 @@ public class ImmutableEntityIntegrationTest {
* {@link ImmutableRecord#getRandomNumber()} gets set via {@link ApplicationConfiguration#beforeConvertCallback()}.
*/
@Test
public void setsRandomNumberOnSaveRecord() {
void setsRandomNumberOnSaveRecord() {
var unsaved = new ImmutableRecord(null, 0);
assertThat(unsaved.randomNumber()).isZero();

View File

@@ -15,33 +15,27 @@
*/
package example.springdata.mongodb.projections;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Collection;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.projection.TargetAware;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Integration tests for {@link CustomerRepository} to show projection capabilities.
*
* @author Oliver Gierke
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class CustomerRepositoryIntegrationTest {
@DataMongoTest
class CustomerRepositoryIntegrationTest {
@Configuration
@EnableAutoConfiguration
@@ -49,10 +43,10 @@ public class CustomerRepositoryIntegrationTest {
@Autowired CustomerRepository customers;
Customer dave, carter;
private Customer dave, carter;
@Before
public void setUp() {
@BeforeEach
void setUp() {
customers.deleteAll();
@@ -61,60 +55,60 @@ public class CustomerRepositoryIntegrationTest {
}
@Test
public void projectsEntityIntoInterface() {
void projectsEntityIntoInterface() {
var result = customers.findAllProjectedBy();
assertThat(result, hasSize(2));
assertThat(result.iterator().next().getFirstname(), is("Dave"));
assertThat(result).hasSize(2);
assertThat(result.iterator().next().getFirstname()).isEqualTo("Dave");
}
@Test
public void projectsToDto() {
void projectsToDto() {
var result = customers.findAllDtoedBy();
assertThat(result, hasSize(2));
assertThat(result.iterator().next().firstname(), is("Dave"));
assertThat(result).hasSize(2);
assertThat(result.iterator().next().firstname()).isEqualTo("Dave");
}
@Test
public void projectsDynamically() {
void projectsDynamically() {
var result = customers.findByFirstname("Dave", CustomerProjection.class);
assertThat(result, hasSize(1));
assertThat(result.iterator().next().getFirstname(), is("Dave"));
assertThat(result).hasSize(1);
assertThat(result.iterator().next().getFirstname()).isEqualTo("Dave");
}
@Test
public void projectsIndividualDynamically() {
void projectsIndividualDynamically() {
var result = customers.findProjectedById(dave.getId(), CustomerSummary.class);
assertThat(result, is(notNullValue()));
assertThat(result.getFullName(), is("Dave Matthews"));
assertThat(result).isNotNull();
assertThat(result.getFullName()).isEqualTo("Dave Matthews");
// Proxy backed by original instance as the projection uses dynamic elements
assertThat(((TargetAware) result).getTarget(), is(instanceOf(Customer.class)));
assertThat(((TargetAware) result).getTarget()).isInstanceOf(Customer.class);
}
@Test
public void projectIndividualInstance() {
void projectIndividualInstance() {
var result = customers.findProjectedById(dave.getId());
assertThat(result, is(notNullValue()));
assertThat(result.getFirstname(), is("Dave"));
assertThat(((TargetAware) result).getTarget(), is(instanceOf(Customer.class)));
assertThat(result).isNotNull();
assertThat(result.getFirstname()).isEqualTo("Dave");
assertThat(((TargetAware) result).getTarget()).isInstanceOf(Customer.class);
}
@Test
public void supportsProjectionInCombinationWithPagination() {
void supportsProjectionInCombinationWithPagination() {
var page = customers
.findPagedProjectedBy(PageRequest.of(0, 1, Sort.by(Direction.ASC, "lastname")));
assertThat(page.getContent().get(0).getFirstname(), is("Carter"));
assertThat(page.getContent().get(0).getFirstname()).isEqualTo("Carter");
}
}

View File

@@ -23,11 +23,11 @@ import static org.springframework.data.mongodb.core.query.Update.*;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResults;
@@ -35,9 +35,6 @@ import org.springframework.data.mongodb.core.ExecutableFindOperation.Terminating
import org.springframework.data.mongodb.core.FluentMongoOperations;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.test.context.junit4.SpringRunner;
import com.mongodb.client.result.UpdateResult;
/**
* Some tests showing usage and capabilities of {@link FluentMongoOperations}. <br />
@@ -53,22 +50,21 @@ import com.mongodb.client.result.UpdateResult;
*
* @author Christoph Strobl
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class FluentMongoApiTests {
@DataMongoTest
class FluentMongoApiTests {
@Autowired FluentMongoOperations mongoOps;
/**
* A predefined, reusable lookup method.
*/
TerminatingFind<Jedi> findLuke;
private TerminatingFind<Jedi> findLuke;
final NearQuery alderaanWithin3Parsecs = NearQuery.near(-73.9667, 40.78).maxDistance(new Distance(3, MILES))
private final NearQuery alderaanWithin3Parsecs = NearQuery.near(-73.9667, 40.78).maxDistance(new Distance(3, MILES))
.spherical(true);
@Before
public void setUp() {
@BeforeEach
void setUp() {
findLuke = mongoOps.query(SWCharacter.class) // SWCharacter does only define the collection, id and name
.as(Jedi.class) // so we use Jedi as the desired return type to also map "lastname"
@@ -91,7 +87,7 @@ public class FluentMongoApiTests {
* </pre>
*/
@Test
public void usePredefinedFinder() {
void usePredefinedFinder() {
assertThat(findLuke.one()).contains(new Jedi("luke", "skywalker"));
}
@@ -109,7 +105,7 @@ public class FluentMongoApiTests {
* </pre>
*/
@Test
public void fetchInterfaceProjection() {
void fetchInterfaceProjection() {
var anakin = mongoOps.query(SWCharacter.class) // SWCharacter does only define the collection, id and name
.as(Sith.class) // use an interface as return type to create a projection
@@ -146,7 +142,7 @@ public class FluentMongoApiTests {
* </pre>
*/
@Test
public void queryFirstVsOne() {
void queryFirstVsOne() {
mongoOps.query(SWCharacter.class) // SWCharacter does only define the collection, id and name
.matching(query(where("lastname").is("skywalker"))) // so properties are taken as is
@@ -177,7 +173,7 @@ public class FluentMongoApiTests {
* </pre>
*/
@Test
public void geoNearQuery() {
void geoNearQuery() {
var results = mongoOps.query(SWCharacter.class) // SWCharacter defines collection, id and name
.as(Jedi.class) // but we want to map the results to Jedi
@@ -202,7 +198,7 @@ public class FluentMongoApiTests {
* </pre>
*/
@Test
public void querySpecificCollection() {
void querySpecificCollection() {
var skywalkers = mongoOps.query(Human.class) // Human does not define a collection via @Document
.inCollection("star-wars") // so we set an explicit collection name
@@ -216,7 +212,7 @@ public class FluentMongoApiTests {
* Simple insert operation adding a new {@link Jedi} to the {@literal star-wars} collection.
*/
@Test
public void justInsertOne() {
void justInsertOne() {
var chewbacca = new SWCharacter("Chewbacca");
@@ -239,7 +235,7 @@ public class FluentMongoApiTests {
* </pre>
*/
@Test
public void updateAndUpsert() {
void updateAndUpsert() {
var result = mongoOps.update(Jedi.class) // Jedi defines the collection and field mapping
.matching(query(where("lastname").is("windu"))) // so "last" maps to "lastname".

View File

@@ -16,10 +16,10 @@
package example.springdata.mongodb.geojson;
import org.bson.Document;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.data.geo.Point;
import org.springframework.data.geo.Polygon;
import org.springframework.data.mongodb.core.MongoOperations;
@@ -28,7 +28,6 @@ import org.springframework.data.mongodb.core.geo.GeoJson;
import org.springframework.data.mongodb.core.geo.GeoJsonPolygon;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Integration tests for {@link StoreRepository}.
@@ -36,9 +35,8 @@ import org.springframework.test.context.junit4.SpringRunner;
* @author Christoph Strobl
* @author Oliver Gierke
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class StoreRepositoryTests {
@DataMongoTest
class StoreRepositoryTests {
private static final GeoJsonPolygon GEO_JSON_POLYGON = new GeoJsonPolygon(new Point(-73.992514, 40.758934),
new Point(-73.961138, 40.760348), new Point(-73.991658, 40.730006), new Point(-73.992514, 40.758934));
@@ -81,7 +79,7 @@ public class StoreRepositoryTests {
* <pre>
*/
@Test
public void findWithinGeoJsonPolygon() {
void findWithinGeoJsonPolygon() {
repository.findByLocationWithin(GEO_JSON_POLYGON).forEach(System.out::println);
}
@@ -102,7 +100,7 @@ public class StoreRepositoryTests {
* <pre>
*/
@Test
public void findWithinLegacyPolygon() {
void findWithinLegacyPolygon() {
repository.findByLocationWithin(new Polygon(new Point(-73.992514, 40.758934), new Point(-73.961138, 40.760348),
new Point(-73.991658, 40.730006))).forEach(System.out::println);
}
@@ -112,7 +110,7 @@ public class StoreRepositoryTests {
* creation of the query using the registered {@link MongoConverter} for {@link GeoJson} conversion.
*/
@Test
public void findStoresThatIntersectGivenPolygon() {
void findStoresThatIntersectGivenPolygon() {
var geoJsonDbo = new Document();

View File

@@ -24,39 +24,34 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StreamUtils;
import com.mongodb.client.gridfs.model.GridFSFile;
/**
* Tests to show the usage of {@link GridFsOperations} with Spring Data MongoDB.
*
* @author Hartmut Lang
* @author Mark Paluch
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class GridFsTests {
@DataMongoTest
class GridFsTests {
@Autowired GridFsOperations gridFsOperations;
@Before
public void before() {
@BeforeEach
void before() {
gridFsOperations.delete(new Query());
}
@Test
public void shouldStoreSimpleFile() throws IOException {
void shouldStoreSimpleFile() throws IOException {
try (InputStream is = new BufferedInputStream(new ClassPathResource("./example-file.txt").getInputStream())) {
// store file
@@ -71,7 +66,7 @@ public class GridFsTests {
}
@Test
public void shouldStoreFileWithMetadata() throws IOException {
void shouldStoreFileWithMetadata() throws IOException {
try (InputStream is = new BufferedInputStream(new ClassPathResource("./example-file.txt").getInputStream())) {
@@ -86,7 +81,7 @@ public class GridFsTests {
}
@Test
public void shouldStoreAndReadFile() throws IOException {
void shouldStoreAndReadFile() throws IOException {
byte[] bytes;
try (InputStream is = new BufferedInputStream(new ClassPathResource("./example-file.txt").getInputStream())) {

View File

@@ -26,14 +26,14 @@ import lombok.RequiredArgsConstructor;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
/**
* @author Oliver Drotbohm
*/
@SpringBootTest
@DataMongoTest
@RequiredArgsConstructor
class ApplicationIntegrationTests {

View File

@@ -17,20 +17,18 @@ package example.springdata.mongodb.people
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.reactive.awaitSingle
import kotlinx.coroutines.reactive.asFlow
import kotlinx.coroutines.reactive.awaitSingle
import kotlinx.coroutines.runBlocking
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest
import org.springframework.data.mongodb.core.*
import org.springframework.data.mongodb.core.query.Criteria.where
import org.springframework.data.mongodb.core.query.Query
import org.springframework.data.mongodb.core.query.isEqualTo
import org.springframework.test.context.junit4.SpringRunner
import reactor.test.StepVerifier
/**
@@ -38,27 +36,29 @@ import reactor.test.StepVerifier
*
* @author Christoph Strobl
*/
@RunWith(SpringRunner::class)
@SpringBootTest
@DataMongoTest
class FlowAndCoroutinesTests {
@Autowired
lateinit var operations: ReactiveMongoOperations
@Before
@BeforeEach
fun before() {
StepVerifier.create(operations.dropCollection<Person>()).verifyComplete()
operations.dropCollection<Person>().`as`(StepVerifier::create).verifyComplete()
}
@Test
fun `find - the coroutine way`() {
StepVerifier.create(operations.insert<Person>().one(Person("Tyrion", "Lannister"))).expectNextCount(1).verifyComplete()
StepVerifier.create(
operations.insert<Person>().one(Person("Tyrion", "Lannister"))
).expectNextCount(1).verifyComplete()
assertThat(
runBlocking {
operations.find<Person>(Query(where("firstname").isEqualTo("Tyrion"))).awaitSingle()
}
runBlocking {
operations.find<Person>(Query(where("firstname").isEqualTo("Tyrion")))
.awaitSingle()
}
).extracting("firstname").isEqualTo("Tyrion")
}

View File

@@ -16,10 +16,11 @@
package example.springdata.mongodb.people;
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.data.mongodb.core.MongoOperations
import org.springframework.data.mongodb.core.dropCollection
@@ -36,14 +37,13 @@ import org.springframework.test.context.junit4.SpringRunner
*
* @author Christoph Strobl
*/
@RunWith(SpringRunner::class)
@SpringBootTest
@DataMongoTest
class MongoDslTests {
@Autowired
lateinit var operations: MongoOperations
@Before
@BeforeEach
fun before() {
operations.dropCollection<Person>()
}

View File

@@ -17,27 +17,24 @@ package example.springdata.mongodb.people
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest
import org.springframework.dao.EmptyResultDataAccessException
import org.springframework.test.context.junit4.SpringRunner
/**
* Tests showing Kotlin usage of Spring Data Repositories.
*
* @author Mark Paluch
*/
@RunWith(SpringRunner::class)
@SpringBootTest
@DataMongoTest
class RepositoryTests {
@Autowired
lateinit var repository: PersonRepository
@Before
@BeforeEach
fun before() {
repository.deleteAll()
}

View File

@@ -17,30 +17,27 @@ package example.springdata.mongodb.people
import org.assertj.core.api.Assertions.assertThat
import org.bson.Document
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest
import org.springframework.data.mongodb.core.*
import org.springframework.data.mongodb.core.query.Criteria.where
import org.springframework.data.mongodb.core.query.Query.query
import org.springframework.data.mongodb.core.query.isEqualTo
import org.springframework.test.context.junit4.SpringRunner
/**
* Tests showing Kotlin usage of [MongoTemplate] and its Kotlin extensions.
*
* @author Mark Paluch
*/
@RunWith(SpringRunner::class)
@SpringBootTest
@DataMongoTest
class TemplateTests {
@Autowired
lateinit var operations: MongoOperations
@Before
@BeforeEach
fun before() {
operations.dropCollection<Person>()
}

View File

@@ -15,21 +15,16 @@
*/
package example.springdata.mongodb.querybyexample;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.domain.ExampleMatcher.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher.StringMatcher;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Integration test showing the usage of MongoDB Query-by-Example support through Spring Data repositories for a case
@@ -39,19 +34,18 @@ import org.springframework.test.context.junit4.SpringRunner;
* @author Oliver Gierke
* @soundtrack Paul van Dyk - VONYC Sessions Episode 496 with guest Armin van Buuren
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class ContactRepositoryIntegrationTests {
@DataMongoTest
class ContactRepositoryIntegrationTests {
@Autowired UserRepository userRepository;
@Autowired ContactRepository contactRepository;
@Autowired MongoOperations mongoOperations;
Person skyler, walter, flynn;
Relative marie, hank;
private Person skyler, walter, flynn;
private Relative marie, hank;
@Before
public void setUp() {
@BeforeEach
void setUp() {
contactRepository.deleteAll();
@@ -66,36 +60,36 @@ public class ContactRepositoryIntegrationTests {
* @see #153
*/
@Test
public void countByConcreteSubtypeExample() {
void countByConcreteSubtypeExample() {
var example = Example.of(new Person(null, null, null));
assertThat(userRepository.count(example), is(3L));
assertThat(userRepository.count(example)).isEqualTo(3L);
}
/**
* @see #153
*/
@Test
public void findAllPersonsBySimpleExample() {
void findAllPersonsBySimpleExample() {
var example = Example.of(new Person(".*", null, null), //
matching().withStringMatcher(StringMatcher.REGEX));
assertThat(userRepository.findAll(example), containsInAnyOrder(skyler, walter, flynn));
assertThat(userRepository.findAll(example), not(containsInAnyOrder(hank, marie)));
assertThat(userRepository.findAll(example)).contains(skyler, walter, flynn);
assertThat((Iterable) userRepository.findAll(example)).doesNotContain(hank, marie);
}
/**
* @see #153
*/
@Test
public void findAllRelativesBySimpleExample() {
void findAllRelativesBySimpleExample() {
var example = Example.of(new Relative(".*", null, null), //
matching().withStringMatcher(StringMatcher.REGEX));
assertThat(contactRepository.findAll(example), containsInAnyOrder(hank, marie));
assertThat(contactRepository.findAll(example), not(containsInAnyOrder(skyler, walter, flynn)));
assertThat(contactRepository.findAll(example)).contains(hank, marie);
assertThat((Iterable) contactRepository.findAll(example)).doesNotContain(skyler, walter, flynn);
}
}

View File

@@ -16,8 +16,7 @@
package example.springdata.mongodb.querybyexample;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.data.domain.ExampleMatcher.*;
import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.*;
import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.startsWith;
@@ -26,16 +25,15 @@ import static org.springframework.data.mongodb.core.query.Query.*;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher.StringMatcher;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Integration test showing the usage of MongoDB Query-by-Example support through Spring Data repositories.
@@ -44,16 +42,15 @@ import org.springframework.test.context.junit4.SpringRunner;
* @author Oliver Gierke
*/
@SuppressWarnings("unused")
@RunWith(SpringRunner.class)
@SpringBootTest
public class MongoOperationsIntegrationTests {
@DataMongoTest
class MongoOperationsIntegrationTests {
@Autowired MongoOperations operations;
Person skyler, walter, flynn, marie, hank;
private Person skyler, walter, flynn, marie, hank;
@Before
public void setUp() {
@BeforeEach
void setUp() {
operations.remove(new Query(), Person.class);
@@ -74,74 +71,74 @@ public class MongoOperationsIntegrationTests {
* @see #153
*/
@Test
public void ignoreNullProperties() {
void ignoreNullProperties() {
var query = query(byExample(new Person(null, null, 17)));
assertThat(operations.find(query, Person.class), hasItems(flynn));
assertThat(operations.find(query, Person.class)).contains(flynn);
}
/**
* @see #153
*/
@Test
public void substringMatching() {
void substringMatching() {
var example = Example.of(new Person("er", null, null), matching().//
withStringMatcher(StringMatcher.ENDING));
assertThat(operations.find(query(byExample(example)), Person.class), hasItems(skyler, walter));
assertThat(operations.find(query(byExample(example)), Person.class)).contains(skyler, walter);
}
/**
* @see #154
*/
@Test
public void regexMatching() {
void regexMatching() {
var example = Example.of(new Person("(Skyl|Walt)er", null, null), matching().//
withMatcher("firstname", GenericPropertyMatcher::regex));
assertThat(operations.find(query(byExample(example)), Person.class), hasItems(skyler, walter));
assertThat(operations.find(query(byExample(example)), Person.class)).contains(skyler, walter);
}
/**
* @see #153
*/
@Test
public void matchStartingStringsIgnoreCase() {
void matchStartingStringsIgnoreCase() {
var example = Example.of(new Person("Walter", "WHITE", null), matching(). //
withIgnorePaths("age").//
withMatcher("firstname", startsWith()).//
withMatcher("lastname", ignoreCase()));
assertThat(operations.find(query(byExample(example)), Person.class), hasItems(flynn, walter));
assertThat(operations.find(query(byExample(example)), Person.class)).contains(flynn, walter);
}
/**
* @see #153
*/
@Test
public void configuringMatchersUsingLambdas() {
void configuringMatchersUsingLambdas() {
var example = Example.of(new Person("Walter", "WHITE", null), matching().//
withIgnorePaths("age"). //
withMatcher("firstname", GenericPropertyMatcher::startsWith). //
withMatcher("lastname", GenericPropertyMatcher::ignoreCase));
assertThat(operations.find(query(byExample(example)), Person.class), hasItems(flynn, walter));
assertThat(operations.find(query(byExample(example)), Person.class)).contains(flynn, walter);
}
/**
* @see #153
*/
@Test
public void valueTransformer() {
void valueTransformer() {
var example = Example.of(new Person(null, "White", 99), matching(). //
withMatcher("age", matcher -> matcher.transform(value -> Optional.of(50))));
assertThat(operations.find(query(byExample(example)), Person.class), hasItems(walter));
assertThat(operations.find(query(byExample(example)), Person.class)).contains(walter);
}
}

View File

@@ -21,14 +21,13 @@ import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatc
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher.StringMatcher;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.data.domain.ExampleMatcher.*;
/**
* Integration test showing the usage of MongoDB Query-by-Example support through Spring Data repositories.
@@ -38,16 +37,15 @@ import org.springframework.test.context.junit4.SpringRunner;
* @author Jens Schauder
*/
@SuppressWarnings("unused")
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserRepositoryIntegrationTests {
@DataMongoTest
class UserRepositoryIntegrationTests {
@Autowired UserRepository repository;
Person skyler, walter, flynn, marie, hank;
private Person skyler, walter, flynn, marie, hank;
@Before
public void setUp() {
@BeforeEach
void setUp() {
repository.deleteAll();
@@ -62,7 +60,7 @@ public class UserRepositoryIntegrationTests {
* @see #153
*/
@Test
public void countBySimpleExample() {
void countBySimpleExample() {
var example = Example.of(new Person(null, "White", null));
@@ -73,7 +71,7 @@ public class UserRepositoryIntegrationTests {
* @see #153
*/
@Test
public void ignorePropertiesAndMatchByAge() {
void ignorePropertiesAndMatchByAge() {
var example = Example.of(flynn, matching(). //
withIgnorePaths("firstname", "lastname"));
@@ -85,7 +83,7 @@ public class UserRepositoryIntegrationTests {
* @see #153
*/
@Test
public void substringMatching() {
void substringMatching() {
var example = Example.of(new Person("er", null, null), matching(). //
withStringMatcher(StringMatcher.ENDING));
@@ -97,7 +95,7 @@ public class UserRepositoryIntegrationTests {
* @see #153
*/
@Test
public void regexMatching() {
void regexMatching() {
var example = Example.of(new Person("(Skyl|Walt)er", null, null), matching(). //
withMatcher("firstname", GenericPropertyMatcher::regex));
@@ -109,7 +107,7 @@ public class UserRepositoryIntegrationTests {
* @see #153
*/
@Test
public void matchStartingStringsIgnoreCase() {
void matchStartingStringsIgnoreCase() {
var example = Example.of(new Person("Walter", "WHITE", null), matching(). //
withIgnorePaths("age"). //
@@ -123,7 +121,7 @@ public class UserRepositoryIntegrationTests {
* @see #153
*/
@Test
public void configuringMatchersUsingLambdas() {
void configuringMatchersUsingLambdas() {
var example = Example.of(new Person("Walter", "WHITE", null), matching(). //
withIgnorePaths("age"). //
@@ -137,7 +135,7 @@ public class UserRepositoryIntegrationTests {
* @see #153
*/
@Test
public void valueTransformer() {
void valueTransformer() {
var example = Example.of(new Person(null, "White", 99), matching(). //
withMatcher("age", matcher -> matcher.transform(value -> Optional.of(50))));

View File

@@ -20,29 +20,26 @@ import static org.assertj.core.api.Assertions.*;
import example.springdata.mongodb.Customer;
import example.springdata.mongodb.QCustomer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author Christoph Strobl
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerRepositoryTests {
@DataMongoTest
class CustomerRepositoryTests {
@Autowired CustomerQuerydslRepository repository;
@Autowired MongoOperations operations;
Customer dave, oliver, carter;
private Customer dave, oliver, carter;
@Before
public void setUp() {
@BeforeEach
void setUp() {
repository.deleteAll();
@@ -52,7 +49,7 @@ public class CustomerRepositoryTests {
}
@Test
public void findAllByPredicate() {
void findAllByPredicate() {
assertThat(repository.findAll(QCustomer.customer.lastname.eq("Matthews"))).containsExactlyInAnyOrder(dave, oliver);
}

View File

@@ -19,33 +19,30 @@ import static org.assertj.core.api.Assertions.*;
import example.springdata.mongodb.Customer;
import example.springdata.mongodb.QCustomer;
import org.junit.jupiter.api.Test;
import reactor.test.StepVerifier;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author Christoph Strobl
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class ReactiveCustomerRepositoryTests {
@DataMongoTest
class ReactiveCustomerRepositoryTests {
@Autowired ReactiveCustomerQuerydslRepository repository;
@Autowired MongoOperations operations;
Customer dave, oliver, carter;
private Customer dave, oliver, carter;
@Before
public void setUp() {
@BeforeEach
void setUp() {
repository.deleteAll().as(StepVerifier::create).verifyComplete();
@@ -57,7 +54,7 @@ public class ReactiveCustomerRepositoryTests {
}
@Test
public void findAllByPredicate() {
void findAllByPredicate() {
repository.findAll(QCustomer.customer.lastname.eq("Matthews")) //
.collectList() //

View File

@@ -18,35 +18,32 @@ package example.springdata.mongodb.people;
import static org.assertj.core.api.Assertions.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import rx.RxReactiveStreams;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Integration test for {@link ReactiveMongoTemplate}.
*
* @author Mark Paluch
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class ReactiveMongoTemplateIntegrationTest {
@DataMongoTest
class ReactiveMongoTemplateIntegrationTest {
@Autowired ReactiveMongoTemplate template;
@Before
public void setUp() {
@BeforeEach
void setUp() {
StepVerifier.create(template.dropCollection(Person.class)).verifyComplete();
@@ -56,7 +53,7 @@ public class ReactiveMongoTemplateIntegrationTest {
new Person("Saul", "Goodman", 42), //
new Person("Jesse", "Pinkman", 27)).collectList());
StepVerifier.create(insertAll).expectNextCount(4).verifyComplete();
insertAll.as(StepVerifier::create).expectNextCount(4).verifyComplete();
}
/**
@@ -64,7 +61,7 @@ public class ReactiveMongoTemplateIntegrationTest {
* the two counts ({@code 4} and {@code 6}) to the console.
*/
@Test
public void shouldInsertAndCountData() {
void shouldInsertAndCountData() {
var count = template.count(new Query(), Person.class) //
.doOnNext(System.out::println) //
@@ -74,14 +71,14 @@ public class ReactiveMongoTemplateIntegrationTest {
.flatMap(v -> template.count(new Query(), Person.class)) //
.doOnNext(System.out::println);//
StepVerifier.create(count).expectNext(6L).verifyComplete();
count.as(StepVerifier::create).expectNext(6L).verifyComplete();
}
/**
* Note that the all object conversions are performed before the results are printed to the console.
*/
@Test
public void convertReactorTypesToRxJava2() {
void convertReactorTypesToRxJava2() {
var flux = template.find(Query.query(Criteria.where("lastname").is("White")), Person.class);

View File

@@ -17,7 +17,6 @@ package example.springdata.mongodb.people;
import static org.assertj.core.api.Assertions.*;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
@@ -25,32 +24,27 @@ import reactor.test.StepVerifier;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.bson.Document;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.data.mongodb.core.CollectionOptions;
import org.springframework.data.mongodb.core.ReactiveMongoOperations;
import org.springframework.test.context.junit4.SpringRunner;
import com.mongodb.reactivestreams.client.MongoCollection;
/**
* Integration test for {@link ReactivePersonRepository} using Project Reactor types and operators.
*
* @author Mark Paluch
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class ReactivePersonRepositoryIntegrationTest {
@DataMongoTest
class ReactivePersonRepositoryIntegrationTest {
@Autowired ReactivePersonRepository repository;
@Autowired ReactiveMongoOperations operations;
@Before
public void setUp() {
@BeforeEach
void setUp() {
var recreateCollection = operations.collectionExists(Person.class) //
.flatMap(exists -> exists ? operations.dropCollection(Person.class) : Mono.just(exists)) //
@@ -59,14 +53,14 @@ public class ReactivePersonRepositoryIntegrationTest {
.maxDocuments(100) //
.capped()));
StepVerifier.create(recreateCollection).expectNextCount(1).verifyComplete();
recreateCollection.as(StepVerifier::create).expectNextCount(1).verifyComplete();
var insertAll = operations.insertAll(Flux.just(new Person("Walter", "White", 50), //
new Person("Skyler", "White", 45), //
new Person("Saul", "Goodman", 42), //
new Person("Jesse", "Pinkman", 27)).collectList());
StepVerifier.create(insertAll).expectNextCount(4).verifyComplete();
insertAll.as(StepVerifier::create).expectNextCount(4).verifyComplete();
}
/**
@@ -74,7 +68,7 @@ public class ReactivePersonRepositoryIntegrationTest {
* the two counts ({@code 4} and {@code 6}) to the console.
*/
@Test
public void shouldInsertAndCountData() {
void shouldInsertAndCountData() {
var saveAndCount = repository.count() //
.doOnNext(System.out::println) //
@@ -84,16 +78,17 @@ public class ReactivePersonRepositoryIntegrationTest {
.flatMap(v -> repository.count()) //
.doOnNext(System.out::println);
StepVerifier.create(saveAndCount).expectNext(6L).verifyComplete();
saveAndCount.as(StepVerifier::create).expectNext(6L).verifyComplete();
}
/**
* Note that the all object conversions are performed before the results are printed to the console.
*/
@Test
public void shouldPerformConversionBeforeResultProcessing() {
void shouldPerformConversionBeforeResultProcessing() {
StepVerifier.create(repository.findAll().doOnNext(System.out::println)) //
repository.findAll().doOnNext(System.out::println) //
.as(StepVerifier::create) //
.expectNextCount(4) //
.verifyComplete();
}
@@ -102,7 +97,7 @@ public class ReactivePersonRepositoryIntegrationTest {
* A tailable cursor streams data using {@link Flux} as it arrives inside the capped collection.
*/
@Test
public void shouldStreamDataWithTailableCursor() throws Exception {
void shouldStreamDataWithTailableCursor() throws Exception {
Queue<Person> people = new ConcurrentLinkedQueue<>();
@@ -115,19 +110,22 @@ public class ReactivePersonRepositoryIntegrationTest {
Thread.sleep(100);
StepVerifier.create(repository.save(new Person("Tuco", "Salamanca", 33))) //
repository.save(new Person("Tuco", "Salamanca", 33)) //
.as(StepVerifier::create) //
.expectNextCount(1) //
.verifyComplete();
Thread.sleep(100);
StepVerifier.create(repository.save(new Person("Mike", "Ehrmantraut", 62))) //
repository.save(new Person("Mike", "Ehrmantraut", 62)) //
.as(StepVerifier::create) //
.expectNextCount(1) //
.verifyComplete();
Thread.sleep(100);
disposable.dispose();
StepVerifier.create(repository.save(new Person("Gus", "Fring", 53))) //
repository.save(new Person("Gus", "Fring", 53)) //
.as(StepVerifier::create) //
.expectNextCount(1) //
.verifyComplete();
Thread.sleep(100);
@@ -139,33 +137,34 @@ public class ReactivePersonRepositoryIntegrationTest {
* Fetch data using query derivation.
*/
@Test
public void shouldQueryDataWithQueryDerivation() {
StepVerifier.create(repository.findByLastname("White")).expectNextCount(2).verifyComplete();
void shouldQueryDataWithQueryDerivation() {
repository.findByLastname("White").as(StepVerifier::create).expectNextCount(2).verifyComplete();
}
/**
* Fetch data using a string query.
*/
@Test
public void shouldQueryDataWithStringQuery() {
StepVerifier.create(repository.findByFirstnameAndLastname("Walter", "White")).expectNextCount(1).verifyComplete();
void shouldQueryDataWithStringQuery() {
repository.findByFirstnameAndLastname("Walter", "White").as(StepVerifier::create).expectNextCount(1)
.verifyComplete();
}
/**
* Fetch data using query derivation.
*/
@Test
public void shouldQueryDataWithDeferredQueryDerivation() {
StepVerifier.create(repository.findByLastname(Mono.just("White"))).expectNextCount(2).verifyComplete();
void shouldQueryDataWithDeferredQueryDerivation() {
repository.findByLastname(Mono.just("White")).as(StepVerifier::create).expectNextCount(2).verifyComplete();
}
/**
* Fetch data using query derivation and deferred parameter resolution.
*/
@Test
public void shouldQueryDataWithMixedDeferredQueryDerivation() {
void shouldQueryDataWithMixedDeferredQueryDerivation() {
StepVerifier.create(repository.findByFirstnameAndLastname(Mono.just("Walter"), "White")) //
repository.findByFirstnameAndLastname(Mono.just("Walter"), "White").as(StepVerifier::create) //
.expectNextCount(1) //
.verifyComplete();
}

View File

@@ -19,24 +19,19 @@ import static org.assertj.core.api.Assertions.*;
import io.reactivex.Flowable;
import io.reactivex.Single;
import io.reactivex.disposables.Disposable;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.bson.Document;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.data.mongodb.core.CollectionOptions;
import org.springframework.data.mongodb.core.ReactiveMongoOperations;
import org.springframework.test.context.junit4.SpringRunner;
import com.mongodb.reactivestreams.client.MongoCollection;
/**
* Integration test for {@link RxJava2PersonRepository} using RxJava2 types. Note that {@link ReactiveMongoOperations}
@@ -47,15 +42,14 @@ import com.mongodb.reactivestreams.client.MongoCollection;
* @author Jens Schauder
* @author Christoph Strobl
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class RxJava2PersonRepositoryIntegrationTest {
@DataMongoTest
class RxJava2PersonRepositoryIntegrationTest {
@Autowired RxJava2PersonRepository repository;
@Autowired ReactiveMongoOperations operations;
@Before
public void setUp() {
@BeforeEach
void setUp() {
var recreateCollection = operations.collectionExists(Person.class) //
.flatMap(exists -> exists ? operations.dropCollection(Person.class) : Mono.just(exists)) //
@@ -81,7 +75,7 @@ public class RxJava2PersonRepositoryIntegrationTest {
* the two counts ({@code 4} and {@code 6}) to the console.
*/
@Test
public void shouldInsertAndCountData() {
void shouldInsertAndCountData() {
var people = Flowable.just(new Person("Hank", "Schrader", 43), //
new Person("Mike", "Ehrmantraut", 62));
@@ -105,7 +99,7 @@ public class RxJava2PersonRepositoryIntegrationTest {
* Note that the all object conversions are performed before the results are printed to the console.
*/
@Test
public void shouldPerformConversionBeforeResultProcessing() {
void shouldPerformConversionBeforeResultProcessing() {
repository.findAll() //
.doOnNext(System.out::println) //
@@ -120,7 +114,7 @@ public class RxJava2PersonRepositoryIntegrationTest {
* A tailable cursor streams data using {@link Flowable} as it arrives inside the capped collection.
*/
@Test
public void shouldStreamDataWithTailableCursor() throws Exception {
void shouldStreamDataWithTailableCursor() throws Exception {
Queue<Person> people = new ConcurrentLinkedQueue<>();
@@ -151,7 +145,7 @@ public class RxJava2PersonRepositoryIntegrationTest {
* Fetch data using query derivation.
*/
@Test
public void shouldQueryDataWithQueryDerivation() {
void shouldQueryDataWithQueryDerivation() {
repository.findByLastname("White") //
.test() //
@@ -165,7 +159,7 @@ public class RxJava2PersonRepositoryIntegrationTest {
* Fetch data using a string query.
*/
@Test
public void shouldQueryDataWithStringQuery() {
void shouldQueryDataWithStringQuery() {
repository.findByFirstnameAndLastname("Walter", "White") //
.test() //
@@ -178,7 +172,7 @@ public class RxJava2PersonRepositoryIntegrationTest {
* Fetch data using query derivation.
*/
@Test
public void shouldQueryDataWithDeferredQueryDerivation() {
void shouldQueryDataWithDeferredQueryDerivation() {
repository.findByLastname(Single.just("White")) //
.test() //
@@ -191,7 +185,7 @@ public class RxJava2PersonRepositoryIntegrationTest {
* Fetch data using query derivation and deferred parameter resolution.
*/
@Test
public void shouldQueryDataWithMixedDeferredQueryDerivation() {
void shouldQueryDataWithMixedDeferredQueryDerivation() {
repository.findByFirstnameAndLastname(Single.just("Walter"), "White") //
.test() //

View File

@@ -19,31 +19,29 @@ import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.core.schema.JsonSchemaProperty.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.mongodb.core.CollectionOptions;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.schema.MongoJsonSchema;
import org.springframework.data.mongodb.core.validation.Validator;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author Christoph Strobl
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class DocumentValidation {
@DataMongoTest
class DocumentValidationTests {
static final String COLLECTION = "star-wars";
private static final String COLLECTION = "star-wars";
@Autowired MongoOperations mongoOps;
@Before
public void setUp() {
@BeforeEach
void setUp() {
mongoOps.dropCollection(COLLECTION);
}
@@ -72,7 +70,7 @@ public class DocumentValidation {
* </pre>
*/
@Test
public void criteriaValidator() {
void criteriaValidator() {
var validator = Validator.criteria( //
where("name").exists(true).ne(null).type(2) // non null String
@@ -114,7 +112,7 @@ public class DocumentValidation {
* </pre>
*/
@Test
public void schemaValidator() {
void schemaValidator() {
var validator = Validator.schema(MongoJsonSchema.builder() //
.required("name", "age") //

View File

@@ -20,28 +20,26 @@ import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.core.query.Query.*;
import static org.springframework.data.mongodb.core.schema.JsonSchemaProperty.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.schema.MongoJsonSchema;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author Christoph Strobl
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SchemaQuery {
@DataMongoTest
class SchemaQueryTests {
static final String COLLECTION = "star-wars";
private static final String COLLECTION = "star-wars";
@Autowired MongoOperations mongoOps;
@Before
public void setUp() {
@BeforeEach
void setUp() {
mongoOps.dropCollection(COLLECTION);
}
@@ -73,7 +71,7 @@ public class SchemaQuery {
* </pre>
*/
@Test
public void criteriaValidator() {
void criteriaValidator() {
var luke = new Jedi("luke", "luke", "skywalker", 25);
var yoda = new Jedi("yoda", "yoda", null, 900);

View File

@@ -15,21 +15,18 @@
*/
package example.springdata.mongodb.security;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Collections;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Integration test for {@link PersonRepository}.
@@ -37,16 +34,15 @@ import org.springframework.test.context.junit4.SpringRunner;
* @author Thomas Darimont
* @author Oliver Gierke
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonRepositoryIntegrationTest {
class PersonRepositoryIntegrationTest {
@Autowired PersonRepository repository;
Person dave, oliver, carter, admin;
private Person dave, oliver, carter, admin;
@Before
public void setUp() {
@BeforeEach
void setUp() {
repository.deleteAll();
@@ -57,18 +53,17 @@ public class PersonRepositoryIntegrationTest {
}
@Test
public void nonAdminCallingShouldReturnOnlyItSelfAsPerson() throws Exception {
void nonAdminCallingShouldReturnOnlyItSelfAsPerson() throws Exception {
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(dave, "x"));
var persons = repository.findAllForCurrentUserById();
assertThat(persons, hasSize(1));
assertThat(persons, contains(dave));
assertThat(persons).hasSize(1).containsExactly(dave);
}
@Test
public void adminCallingShouldReturnAllUsers() throws Exception {
void adminCallingShouldReturnAllUsers() throws Exception {
var auth = new UsernamePasswordAuthenticationToken(admin, "x",
Collections.singleton(new SimpleGrantedAuthority("ROLE_ADMIN")));
@@ -76,7 +71,6 @@ public class PersonRepositoryIntegrationTest {
var persons = repository.findAllForCurrentUserById();
assertThat(persons, hasSize(4));
assertThat(persons, containsInAnyOrder(admin, dave, carter, oliver));
assertThat(persons).hasSize(4).contains(admin, dave, carter, oliver);
}
}

View File

@@ -17,15 +17,12 @@ package example.springdata.mongodb.textsearch;
import static example.springdata.mongodb.util.ConsoleResultPrinter.*;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.data.mongodb.core.mapping.TextScore;
import org.springframework.data.mongodb.core.query.TextCriteria;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Integration tests showing the text search functionality using repositories.
@@ -34,9 +31,8 @@ import org.springframework.test.context.junit4.SpringRunner;
* @author Oliver Gierke
* @author Thomas Darimont
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class TextSearchRepositoryTests {
@DataMongoTest
class TextSearchRepositoryTests {
@Autowired BlogPostRepository repo;
@@ -45,7 +41,7 @@ public class TextSearchRepositoryTests {
* Note that text search is case insensitive and will also find entries like {@literal releases}.
*/
@Test
public void findAllBlogPostsWithRelease() {
void findAllBlogPostsWithRelease() {
var criteria = TextCriteria.forDefaultLanguage().matchingAny("release");
var blogPosts = repo.findAllBy(criteria);
@@ -57,7 +53,7 @@ public class TextSearchRepositoryTests {
* Simple matching using negation.
*/
@Test
public void findAllBlogPostsWithReleaseButHeyIDoWantTheEngineeringStuff() {
void findAllBlogPostsWithReleaseButHeyIDoWantTheEngineeringStuff() {
var criteria = TextCriteria.forDefaultLanguage().matchingAny("release").notMatching("engineering");
var blogPosts = repo.findAllBy(criteria);
@@ -69,7 +65,7 @@ public class TextSearchRepositoryTests {
* Phrase matching looks for the whole phrase as one.
*/
@Test
public void findAllBlogPostsByPhrase() {
void findAllBlogPostsByPhrase() {
var criteria = TextCriteria.forDefaultLanguage().matchingPhrase("release candidate");
var blogPosts = repo.findAllBy(criteria);
@@ -81,7 +77,7 @@ public class TextSearchRepositoryTests {
* Sort by relevance relying on the value marked with {@link TextScore}.
*/
@Test
public void findAllBlogPostsByPhraseSortByScore() {
void findAllBlogPostsByPhraseSortByScore() {
var criteria = TextCriteria.forDefaultLanguage().matchingPhrase("release candidate");
var blogPosts = repo.findAllByOrderByScoreDesc(criteria);

View File

@@ -18,46 +18,29 @@ package example.springdata.mongodb.textsearch;
import static example.springdata.mongodb.util.ConsoleResultPrinter.*;
import static org.springframework.data.mongodb.core.query.Query.*;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.TextCriteria;
import org.springframework.data.mongodb.core.query.TextQuery;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author Christoph Strobl
* @author Thomas Darimont
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class TextSearchTemplateTests {
@DataMongoTest
class TextSearchTemplateTests {
@Autowired MongoOperations operations;
// @Before
// public void setUp() throws Exception {
//
// MongoProperties properties = new MongoProperties();
//
// operations = new MongoTemplate(properties.createMongoClient(null), properties.getMongoClientDatabase());
// operations.dropCollection(BlogPost.class);
//
// createIndex();
//
// BlogPostInitializer.INSTANCE.initialize(this.operations);
// }
/**
* Show how to do simple matching. Note that text search is case insensitive and will also find entries like
* {@literal releases}.
*/
@Test
public void findAllBlogPostsWithRelease() {
void findAllBlogPostsWithRelease() {
var criteria = TextCriteria.forDefaultLanguage().matchingAny("release");
var blogPosts = operations.find(query(criteria), BlogPost.class);
@@ -69,7 +52,7 @@ public class TextSearchTemplateTests {
* Sort by relevance relying on the value marked with {@link org.springframework.data.mongodb.core.mapping.TextScore}.
*/
@Test
public void findAllBlogPostsByPhraseSortByScore() {
void findAllBlogPostsByPhraseSortByScore() {
var criteria = TextCriteria.forDefaultLanguage().matchingPhrase("release");