Browse Source

DATAMONGO-2199 - Move tests to AssertJ.

Original pull request: #643.
pull/646/head
Christoph Strobl 7 years ago committed by Mark Paluch
parent
commit
45f4b5087c
  1. 23
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoClientParserIntegrationTests.java
  2. 38
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoDbFactoryParserIntegrationTests.java
  3. 7
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/StringToWriteConcernConverterUnitTests.java
  4. 7
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/WriteConcernPropertyEditorUnitTests.java
  5. 29
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultIndexOperationsIntegrationTests.java
  6. 38
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/SerializationUtilsUnitTests.java
  7. 19
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/AbstractGeoSpatialTests.java
  8. 45
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoJsonTests.java
  9. 17
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoSpatialIndexTests.java
  10. 19
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/index/TextIndexTests.java
  11. 6
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/GeoIndexedTests.java
  12. 131
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/QueryTests.java

23
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoClientParserIntegrationTests.java

@ -15,11 +15,7 @@
*/ */
package org.springframework.data.mongodb.config; package org.springframework.data.mongodb.config;
import static org.hamcrest.collection.IsIterableContainingInOrder.*; import static org.assertj.core.api.Assertions.*;
import static org.hamcrest.core.Is.*;
import static org.hamcrest.core.IsInstanceOf.*;
import static org.junit.Assert.*;
import static org.junit.Assume.*;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -29,7 +25,6 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericApplicationContext; import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.data.mongodb.util.MongoClientVersion;
import com.mongodb.MongoClient; import com.mongodb.MongoClient;
import com.mongodb.MongoCredential; import com.mongodb.MongoCredential;
@ -59,7 +54,7 @@ public class MongoClientParserIntegrationTests {
reader.loadBeanDefinitions(new ClassPathResource("namespace/mongoClient-bean.xml")); reader.loadBeanDefinitions(new ClassPathResource("namespace/mongoClient-bean.xml"));
assertThat(factory.getBean("mongo-client-with-host-and-port"), instanceOf(MongoClient.class)); assertThat(factory.getBean("mongo-client-with-host-and-port")).isInstanceOf(MongoClient.class);
} }
@Test // DATAMONGO-1158, DATAMONGO-2199 @Test // DATAMONGO-1158, DATAMONGO-2199
@ -74,8 +69,8 @@ public class MongoClientParserIntegrationTests {
MongoClient client = context.getBean("mongo-client-with-options-for-write-concern-and-read-preference", MongoClient client = context.getBean("mongo-client-with-options-for-write-concern-and-read-preference",
MongoClient.class); MongoClient.class);
assertThat(client.getReadPreference(), is(ReadPreference.secondary())); assertThat(client.getReadPreference()).isEqualTo(ReadPreference.secondary());
assertThat(client.getWriteConcern(), is(WriteConcern.UNACKNOWLEDGED)); assertThat(client.getWriteConcern()).isEqualTo(WriteConcern.UNACKNOWLEDGED);
} finally { } finally {
context.close(); context.close();
} }
@ -92,8 +87,8 @@ public class MongoClientParserIntegrationTests {
try { try {
MongoClient client = context.getBean("mongoClient", MongoClient.class); MongoClient client = context.getBean("mongoClient", MongoClient.class);
assertThat(client.getAddress().getHost(), is("127.0.0.1")); assertThat(client.getAddress().getHost()).isEqualTo("127.0.0.1");
assertThat(client.getAddress().getPort(), is(27017)); assertThat(client.getAddress().getPort()).isEqualTo(27017);
} finally { } finally {
context.close(); context.close();
} }
@ -110,8 +105,8 @@ public class MongoClientParserIntegrationTests {
try { try {
MongoClient client = context.getBean("mongo-client-with-credentials", MongoClient.class); MongoClient client = context.getBean("mongo-client-with-credentials", MongoClient.class);
assertThat(client.getCredentialsList(), assertThat(client.getCredentialsList())
contains(MongoCredential.createPlainCredential("jon", "snow", "warg".toCharArray()))); .contains(MongoCredential.createPlainCredential("jon", "snow", "warg".toCharArray()));
} finally { } finally {
context.close(); context.close();
} }
@ -128,7 +123,7 @@ public class MongoClientParserIntegrationTests {
try { try {
MongoClient client = context.getBean("mongo-client-with-server-selection-timeout", MongoClient.class); MongoClient client = context.getBean("mongo-client-with-server-selection-timeout", MongoClient.class);
assertThat(client.getMongoClientOptions().getServerSelectionTimeout(), is((Object) 100)); assertThat(client.getMongoClientOptions().getServerSelectionTimeout()).isEqualTo(100);
} finally { } finally {
context.close(); context.close();
} }

38
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoDbFactoryParserIntegrationTests.java

@ -15,8 +15,7 @@
*/ */
package org.springframework.data.mongodb.config; package org.springframework.data.mongodb.config;
import static org.hamcrest.Matchers.*; import static org.assertj.core.api.Assertions.*;
import static org.junit.Assert.*;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -64,17 +63,19 @@ public class MongoDbFactoryParserIntegrationTests {
dbFactory.setWriteConcern(WriteConcern.ACKNOWLEDGED); dbFactory.setWriteConcern(WriteConcern.ACKNOWLEDGED);
dbFactory.getDb(); dbFactory.getDb();
assertThat(ReflectionTestUtils.getField(dbFactory, "writeConcern"), is((Object) WriteConcern.ACKNOWLEDGED)); assertThat(ReflectionTestUtils.getField(dbFactory, "writeConcern")).isEqualTo(WriteConcern.ACKNOWLEDGED);
} }
@Test // DATAMONGO-2199 @Test // DATAMONGO-2199
public void parsesWriteConcern() { public void parsesWriteConcern() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("namespace/db-factory-bean.xml"); ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("namespace/db-factory-bean.xml");
assertWriteConcern(ctx, WriteConcern.ACKNOWLEDGED); assertWriteConcern(ctx, WriteConcern.ACKNOWLEDGED);
} }
@Test // DATAMONGO-2199 @Test // DATAMONGO-2199
public void parsesCustomWriteConcern() { public void parsesCustomWriteConcern() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"namespace/db-factory-bean-custom-write-concern.xml"); "namespace/db-factory-bean-custom-write-concern.xml");
assertWriteConcern(ctx, new WriteConcern("rack1")); assertWriteConcern(ctx, new WriteConcern("rack1"));
@ -88,17 +89,18 @@ public class MongoDbFactoryParserIntegrationTests {
MongoDbFactory factory = ctx.getBean("second", MongoDbFactory.class); MongoDbFactory factory = ctx.getBean("second", MongoDbFactory.class);
MongoDatabase db = factory.getDb(); MongoDatabase db = factory.getDb();
assertThat(db.getWriteConcern(), is(WriteConcern.W2)); assertThat(db.getWriteConcern()).isEqualTo(WriteConcern.W2);
ctx.close(); ctx.close();
} }
// This test will fail since equals in WriteConcern uses == for _w and not .equals // This test will fail since equals in WriteConcern uses == for _w and not .equals
public void testWriteConcernEquality() { public void testWriteConcernEquality() {
String s1 = new String("rack1"); String s1 = new String("rack1");
String s2 = new String("rack1"); String s2 = new String("rack1");
WriteConcern wc1 = new WriteConcern(s1); WriteConcern wc1 = new WriteConcern(s1);
WriteConcern wc2 = new WriteConcern(s2); WriteConcern wc2 = new WriteConcern(s2);
assertThat(wc1, is(wc2)); assertThat(wc1).isEqualTo(wc2);
} }
@Test @Test
@ -115,13 +117,13 @@ public class MongoDbFactoryParserIntegrationTests {
BeanDefinition definition = factory.getBeanDefinition("mongoDbFactory"); BeanDefinition definition = factory.getBeanDefinition("mongoDbFactory");
ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues(); ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues();
assertThat(constructorArguments.getArgumentCount(), is(1)); assertThat(constructorArguments.getArgumentCount()).isOne();
ValueHolder argument = constructorArguments.getArgumentValue(0, MongoURI.class); ValueHolder argument = constructorArguments.getArgumentValue(0, MongoURI.class);
assertThat(argument, is(notNullValue())); assertThat(argument).isNotNull();
MongoDbFactory dbFactory = factory.getBean("mongoDbFactory", MongoDbFactory.class); MongoDbFactory dbFactory = factory.getBean("mongoDbFactory", MongoDbFactory.class);
MongoDatabase db = dbFactory.getDb(); MongoDatabase db = dbFactory.getDb();
assertThat(db.getName(), is("database")); assertThat(db.getName()).isEqualTo("database");
} }
@Test // DATAMONGO-1218 @Test // DATAMONGO-1218
@ -131,9 +133,9 @@ public class MongoDbFactoryParserIntegrationTests {
BeanDefinition definition = factory.getBeanDefinition("mongoDbFactory"); BeanDefinition definition = factory.getBeanDefinition("mongoDbFactory");
ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues(); ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues();
assertThat(constructorArguments.getArgumentCount(), is(1)); assertThat(constructorArguments.getArgumentCount()).isOne();
ValueHolder argument = constructorArguments.getArgumentValue(0, MongoClientURI.class); ValueHolder argument = constructorArguments.getArgumentValue(0, MongoClientURI.class);
assertThat(argument, is(notNullValue())); assertThat(argument).isNotNull();
} }
@Test // DATAMONGO-1293 @Test // DATAMONGO-1293
@ -143,9 +145,9 @@ public class MongoDbFactoryParserIntegrationTests {
BeanDefinition definition = factory.getBeanDefinition("testMongo"); BeanDefinition definition = factory.getBeanDefinition("testMongo");
ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues(); ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues();
assertThat(constructorArguments.getArgumentCount(), is(1)); assertThat(constructorArguments.getArgumentCount()).isOne();
ValueHolder argument = constructorArguments.getArgumentValue(0, MongoClientURI.class); ValueHolder argument = constructorArguments.getArgumentValue(0, MongoClientURI.class);
assertThat(argument, is(notNullValue())); assertThat(argument).isNotNull();
} }
@Test // DATAMONGO-1293 @Test // DATAMONGO-1293
@ -155,16 +157,16 @@ public class MongoDbFactoryParserIntegrationTests {
BeanDefinition definition = factory.getBeanDefinition("testMongo"); BeanDefinition definition = factory.getBeanDefinition("testMongo");
ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues(); ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues();
assertThat(constructorArguments.getArgumentCount(), is(1)); assertThat(constructorArguments.getArgumentCount()).isOne();
ValueHolder argument = constructorArguments.getArgumentValue(0, MongoClientURI.class); ValueHolder argument = constructorArguments.getArgumentValue(0, MongoClientURI.class);
assertThat(argument, is(notNullValue())); assertThat(argument).isNotNull();
} }
private static void assertWriteConcern(ClassPathXmlApplicationContext ctx, WriteConcern expectedWriteConcern) { private static void assertWriteConcern(ClassPathXmlApplicationContext ctx, WriteConcern expectedWriteConcern) {
SimpleMongoDbFactory dbFactory = ctx.getBean("first", SimpleMongoDbFactory.class); SimpleMongoDbFactory dbFactory = ctx.getBean("first", SimpleMongoDbFactory.class);
MongoDatabase db = dbFactory.getDb(); MongoDatabase db = dbFactory.getDb();
assertThat(db.getName(), is("db")); assertThat(db.getName()).isEqualTo("db");
WriteConcern configuredConcern = (WriteConcern) ReflectionTestUtils.getField(dbFactory, "writeConcern"); WriteConcern configuredConcern = (WriteConcern) ReflectionTestUtils.getField(dbFactory, "writeConcern");
@ -172,8 +174,8 @@ public class MongoDbFactoryParserIntegrationTests {
MyWriteConcern myDbWriteConcern = new MyWriteConcern(db.getWriteConcern()); MyWriteConcern myDbWriteConcern = new MyWriteConcern(db.getWriteConcern());
MyWriteConcern myExpectedWriteConcern = new MyWriteConcern(expectedWriteConcern); MyWriteConcern myExpectedWriteConcern = new MyWriteConcern(expectedWriteConcern);
assertThat(myDbFactoryWriteConcern, is(myExpectedWriteConcern)); assertThat(myDbFactoryWriteConcern).isEqualTo(myExpectedWriteConcern);
assertThat(myDbWriteConcern, is(myExpectedWriteConcern)); assertThat(myDbWriteConcern).isEqualTo(myExpectedWriteConcern);
assertThat(myDbWriteConcern, is(myDbFactoryWriteConcern)); assertThat(myDbWriteConcern).isEqualTo(myDbFactoryWriteConcern);
} }
} }

7
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/StringToWriteConcernConverterUnitTests.java

@ -15,8 +15,7 @@
*/ */
package org.springframework.data.mongodb.config; package org.springframework.data.mongodb.config;
import static org.hamcrest.CoreMatchers.*; import static org.assertj.core.api.Assertions.*;
import static org.junit.Assert.*;
import org.junit.Test; import org.junit.Test;
@ -34,11 +33,11 @@ public class StringToWriteConcernConverterUnitTests {
@Test // DATAMONGO-2199 @Test // DATAMONGO-2199
public void createsWellKnownConstantsCorrectly() { public void createsWellKnownConstantsCorrectly() {
assertThat(converter.convert("ACKNOWLEDGED"), is(WriteConcern.ACKNOWLEDGED)); assertThat(converter.convert("ACKNOWLEDGED")).isEqualTo(WriteConcern.ACKNOWLEDGED);
} }
@Test @Test
public void createsWriteConcernForUnknownValue() { public void createsWriteConcernForUnknownValue() {
assertThat(converter.convert("-1"), is(new WriteConcern("-1"))); assertThat(converter.convert("-1")).isEqualTo(new WriteConcern("-1"));
} }
} }

7
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/WriteConcernPropertyEditorUnitTests.java

@ -15,8 +15,7 @@
*/ */
package org.springframework.data.mongodb.config; package org.springframework.data.mongodb.config;
import static org.hamcrest.CoreMatchers.*; import static org.assertj.core.api.Assertions.*;
import static org.junit.Assert.*;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -42,13 +41,13 @@ public class WriteConcernPropertyEditorUnitTests {
public void createsWriteConcernForWellKnownConstants() { public void createsWriteConcernForWellKnownConstants() {
editor.setAsText("JOURNALED"); editor.setAsText("JOURNALED");
assertThat(editor.getValue(), is((Object) WriteConcern.JOURNALED)); assertThat(editor.getValue()).isEqualTo(WriteConcern.JOURNALED);
} }
@Test @Test
public void createsWriteConcernForUnknownConstants() { public void createsWriteConcernForUnknownConstants() {
editor.setAsText("-1"); editor.setAsText("-1");
assertThat(editor.getValue(), is((Object) new WriteConcern("-1"))); assertThat(editor.getValue()).isEqualTo(new WriteConcern("-1"));
} }
} }

29
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultIndexOperationsIntegrationTests.java

@ -16,8 +16,7 @@
package org.springframework.data.mongodb.core; package org.springframework.data.mongodb.core;
import static org.assertj.core.api.Assertions.*; import static org.assertj.core.api.Assertions.*;
import static org.hamcrest.core.Is.*; import static org.assertj.core.api.Assumptions.*;
import static org.junit.Assume.*;
import static org.springframework.data.mongodb.core.index.PartialIndexFilter.*; import static org.springframework.data.mongodb.core.index.PartialIndexFilter.*;
import static org.springframework.data.mongodb.core.query.Criteria.*; import static org.springframework.data.mongodb.core.query.Criteria.*;
@ -27,13 +26,13 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.query.Collation;
import org.springframework.data.mongodb.core.query.Collation.CaseFirst;
import org.springframework.data.mongodb.core.convert.QueryMapper; import org.springframework.data.mongodb.core.convert.QueryMapper;
import org.springframework.data.mongodb.core.index.Index; import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.IndexDefinition; import org.springframework.data.mongodb.core.index.IndexDefinition;
import org.springframework.data.mongodb.core.index.IndexInfo; import org.springframework.data.mongodb.core.index.IndexInfo;
import org.springframework.data.mongodb.core.mapping.Field; import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.data.mongodb.core.query.Collation;
import org.springframework.data.mongodb.core.query.Collation.CaseFirst;
import org.springframework.data.util.Version; import org.springframework.data.util.Version;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ -93,7 +92,7 @@ public class DefaultIndexOperationsIntegrationTests {
@Test // DATAMONGO-1467, DATAMONGO-2198 @Test // DATAMONGO-1467, DATAMONGO-2198
public void shouldApplyPartialFilterCorrectly() { public void shouldApplyPartialFilterCorrectly() {
assumeThat(mongoVersion.isGreaterThanOrEqualTo(THREE_DOT_TWO), is(true)); assumeThat(mongoVersion.isGreaterThanOrEqualTo(THREE_DOT_TWO)).isTrue();
IndexDefinition id = new Index().named("partial-with-criteria").on("k3y", Direction.ASC) IndexDefinition id = new Index().named("partial-with-criteria").on("k3y", Direction.ASC)
.partial(of(where("q-t-y").gte(10))); .partial(of(where("q-t-y").gte(10)));
@ -101,13 +100,14 @@ public class DefaultIndexOperationsIntegrationTests {
indexOps.ensureIndex(id); indexOps.ensureIndex(id);
IndexInfo info = findAndReturnIndexInfo(indexOps.getIndexInfo(), "partial-with-criteria"); IndexInfo info = findAndReturnIndexInfo(indexOps.getIndexInfo(), "partial-with-criteria");
assertThat(Document.parse(info.getPartialFilterExpression())).isEqualTo(Document.parse("{ \"q-t-y\" : { \"$gte\" : 10 } }")); assertThat(Document.parse(info.getPartialFilterExpression()))
.isEqualTo(Document.parse("{ \"q-t-y\" : { \"$gte\" : 10 } }"));
} }
@Test // DATAMONGO-1467, DATAMONGO-2198 @Test // DATAMONGO-1467, DATAMONGO-2198
public void shouldApplyPartialFilterWithMappedPropertyCorrectly() { public void shouldApplyPartialFilterWithMappedPropertyCorrectly() {
assumeThat(mongoVersion.isGreaterThanOrEqualTo(THREE_DOT_TWO), is(true)); assumeThat(mongoVersion.isGreaterThanOrEqualTo(THREE_DOT_TWO)).isTrue();
IndexDefinition id = new Index().named("partial-with-mapped-criteria").on("k3y", Direction.ASC) IndexDefinition id = new Index().named("partial-with-mapped-criteria").on("k3y", Direction.ASC)
.partial(of(where("quantity").gte(10))); .partial(of(where("quantity").gte(10)));
@ -115,13 +115,14 @@ public class DefaultIndexOperationsIntegrationTests {
indexOps.ensureIndex(id); indexOps.ensureIndex(id);
IndexInfo info = findAndReturnIndexInfo(indexOps.getIndexInfo(), "partial-with-mapped-criteria"); IndexInfo info = findAndReturnIndexInfo(indexOps.getIndexInfo(), "partial-with-mapped-criteria");
assertThat(Document.parse(info.getPartialFilterExpression())).isEqualTo(Document.parse("{ \"qty\" : { \"$gte\" : 10 } }")); assertThat(Document.parse(info.getPartialFilterExpression()))
.isEqualTo(Document.parse("{ \"qty\" : { \"$gte\" : 10 } }"));
} }
@Test // DATAMONGO-1467, DATAMONGO-2198 @Test // DATAMONGO-1467, DATAMONGO-2198
public void shouldApplyPartialDBOFilterCorrectly() { public void shouldApplyPartialDBOFilterCorrectly() {
assumeThat(mongoVersion.isGreaterThanOrEqualTo(THREE_DOT_TWO), is(true)); assumeThat(mongoVersion.isGreaterThanOrEqualTo(THREE_DOT_TWO)).isTrue();
IndexDefinition id = new Index().named("partial-with-dbo").on("k3y", Direction.ASC) IndexDefinition id = new Index().named("partial-with-dbo").on("k3y", Direction.ASC)
.partial(of(new org.bson.Document("qty", new org.bson.Document("$gte", 10)))); .partial(of(new org.bson.Document("qty", new org.bson.Document("$gte", 10))));
@ -129,13 +130,14 @@ public class DefaultIndexOperationsIntegrationTests {
indexOps.ensureIndex(id); indexOps.ensureIndex(id);
IndexInfo info = findAndReturnIndexInfo(indexOps.getIndexInfo(), "partial-with-dbo"); IndexInfo info = findAndReturnIndexInfo(indexOps.getIndexInfo(), "partial-with-dbo");
assertThat(Document.parse(info.getPartialFilterExpression())).isEqualTo(Document.parse("{ \"qty\" : { \"$gte\" : 10 } }")); assertThat(Document.parse(info.getPartialFilterExpression()))
.isEqualTo(Document.parse("{ \"qty\" : { \"$gte\" : 10 } }"));
} }
@Test // DATAMONGO-1467, DATAMONGO-2198 @Test // DATAMONGO-1467, DATAMONGO-2198
public void shouldFavorExplicitMappingHintViaClass() { public void shouldFavorExplicitMappingHintViaClass() {
assumeThat(mongoVersion.isGreaterThanOrEqualTo(THREE_DOT_TWO), is(true)); assumeThat(mongoVersion.isGreaterThanOrEqualTo(THREE_DOT_TWO)).isTrue();
IndexDefinition id = new Index().named("partial-with-inheritance").on("k3y", Direction.ASC) IndexDefinition id = new Index().named("partial-with-inheritance").on("k3y", Direction.ASC)
.partial(of(where("age").gte(10))); .partial(of(where("age").gte(10)));
@ -147,13 +149,14 @@ public class DefaultIndexOperationsIntegrationTests {
indexOps.ensureIndex(id); indexOps.ensureIndex(id);
IndexInfo info = findAndReturnIndexInfo(indexOps.getIndexInfo(), "partial-with-inheritance"); IndexInfo info = findAndReturnIndexInfo(indexOps.getIndexInfo(), "partial-with-inheritance");
assertThat(Document.parse(info.getPartialFilterExpression())).isEqualTo(Document.parse("{ \"a_g_e\" : { \"$gte\" : 10 } }")); assertThat(Document.parse(info.getPartialFilterExpression()))
.isEqualTo(Document.parse("{ \"a_g_e\" : { \"$gte\" : 10 } }"));
} }
@Test // DATAMONGO-1518 @Test // DATAMONGO-1518
public void shouldCreateIndexWithCollationCorrectly() { public void shouldCreateIndexWithCollationCorrectly() {
assumeThat(mongoVersion.isGreaterThanOrEqualTo(THREE_DOT_FOUR), is(true)); assumeThat(mongoVersion.isGreaterThanOrEqualTo(THREE_DOT_FOUR)).isTrue();
IndexDefinition id = new Index().named("with-collation").on("xyz", Direction.ASC) IndexDefinition id = new Index().named("with-collation").on("xyz", Direction.ASC)
.collation(Collation.of("de_AT").caseFirst(CaseFirst.off())); .collation(Collation.of("de_AT").caseFirst(CaseFirst.off()));

38
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/SerializationUtilsUnitTests.java

@ -15,15 +15,13 @@
*/ */
package org.springframework.data.mongodb.core; package org.springframework.data.mongodb.core;
import static org.hamcrest.Matchers.*; import static org.assertj.core.api.Assertions.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.core.query.SerializationUtils.*; import static org.springframework.data.mongodb.core.query.SerializationUtils.*;
import java.util.Arrays; import java.util.Arrays;
import java.util.Map; import java.util.Map;
import org.bson.Document; import org.bson.Document;
import org.hamcrest.Matcher;
import org.junit.Test; import org.junit.Test;
import org.springframework.data.mongodb.core.query.SerializationUtils; import org.springframework.data.mongodb.core.query.SerializationUtils;
@ -41,26 +39,24 @@ public class SerializationUtilsUnitTests {
public void writesSimpleDocument() { public void writesSimpleDocument() {
Document document = new Document("foo", "bar"); Document document = new Document("foo", "bar");
assertThat(serializeToJsonSafely(document), is("{ \"foo\" : \"bar\"}")); assertThat(serializeToJsonSafely(document)).isEqualTo("{ \"foo\" : \"bar\"}");
} }
@Test @Test
public void writesComplexObjectAsPlainToString() { public void writesComplexObjectAsPlainToString() {
Document document = new Document("foo", new Complex()); Document document = new Document("foo", new Complex());
assertThat(serializeToJsonSafely(document), assertThat(serializeToJsonSafely(document).startsWith(
startsWith("{ \"foo\" : { \"$java\" : org.springframework.data.mongodb.core.SerializationUtilsUnitTests$Complex")); "{ \"foo\" : { \"$java\" : org.springframework.data.mongodb.core.SerializationUtilsUnitTests$Complex"));
} }
@Test @Test
public void writesCollection() { public void writesCollection() {
Document document = new Document("foo", Arrays.asList("bar", new Complex())); Document document = new Document("foo", Arrays.asList("bar", new Complex()));
Matcher<String> expectedOutput = allOf( assertThat(serializeToJsonSafely(document)).startsWith(
startsWith( "{ \"foo\" : [ \"bar\", { \"$java\" : org.springframework.data.mongodb.core.SerializationUtilsUnitTests$Complex")
"{ \"foo\" : [ \"bar\", { \"$java\" : org.springframework.data.mongodb.core.SerializationUtilsUnitTests$Complex"), .endsWith(" } ] }");
endsWith(" } ] }"));
assertThat(serializeToJsonSafely(document), is(expectedOutput));
} }
@Test // DATAMONGO-1245 @Test // DATAMONGO-1245
@ -70,8 +66,7 @@ public class SerializationUtilsUnitTests {
document.put("_id", 1); document.put("_id", 1);
document.put("nested", new Document("value", "conflux")); document.put("nested", new Document("value", "conflux"));
assertThat(flattenMap(document), hasEntry("_id", (Object) 1)); assertThat(flattenMap(document)).containsEntry("_id", 1).containsEntry("nested.value", "conflux");
assertThat(flattenMap(document), hasEntry("nested.value", (Object) "conflux"));
} }
@Test // DATAMONGO-1245 @Test // DATAMONGO-1245
@ -84,8 +79,7 @@ public class SerializationUtilsUnitTests {
document.put("_id", 1); document.put("_id", 1);
document.put("nested", new Document("value", dbl)); document.put("nested", new Document("value", dbl));
assertThat(flattenMap(document), hasEntry("_id", (Object) 1)); assertThat(flattenMap(document)).containsEntry("_id", 1).containsEntry("nested.value", dbl);
assertThat(flattenMap(document), hasEntry("nested.value", (Object) dbl));
} }
@Test // DATAMONGO-1245 @Test // DATAMONGO-1245
@ -97,9 +91,8 @@ public class SerializationUtilsUnitTests {
Map<String, Object> map = flattenMap(document); Map<String, Object> map = flattenMap(document);
assertThat(map, hasEntry("_id", (Object) 1)); assertThat(map).containsEntry("_id", 1).containsKey("nested");
assertThat(map.get("nested"), notNullValue()); assertThat(((Map<String, Object>) map.get("nested")).get("$regex")).isEqualTo("^conflux$");
assertThat(((Map<String, Object>) map.get("nested")).get("$regex"), is((Object) "^conflux$"));
} }
@Test // DATAMONGO-1245 @Test // DATAMONGO-1245
@ -114,15 +107,14 @@ public class SerializationUtilsUnitTests {
Map<String, Object> map = flattenMap(document); Map<String, Object> map = flattenMap(document);
assertThat(map, hasEntry("_id", (Object) 1)); assertThat(map).containsEntry("_id", 1).containsKey("nested");
assertThat(map.get("nested"), notNullValue()); assertThat(((Map<String, Object>) map.get("nested")).get("$regex")).isEqualTo("^conflux$");
assertThat(((Map<String, Object>) map.get("nested")).get("$regex"), is((Object) "^conflux$")); assertThat(((Map<String, Object>) map.get("nested")).get("$options")).isEqualTo("i");
assertThat(((Map<String, Object>) map.get("nested")).get("$options"), is((Object) "i"));
} }
@Test // DATAMONGO-1245 @Test // DATAMONGO-1245
public void flattenMapShouldReturnEmptyMapWhenSourceIsNull() { public void flattenMapShouldReturnEmptyMapWhenSourceIsNull() {
assertThat(flattenMap(null).isEmpty(), is(true)); assertThat(flattenMap(null)).isEmpty();
} }
static class Complex { static class Complex {

19
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/AbstractGeoSpatialTests.java

@ -15,8 +15,7 @@
*/ */
package org.springframework.data.mongodb.core.geo; package org.springframework.data.mongodb.core.geo;
import static org.hamcrest.Matchers.*; import static org.assertj.core.api.Assertions.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.core.query.Criteria.*; 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.query.Query.*;
@ -32,7 +31,6 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.data.geo.Box; import org.springframework.data.geo.Box;
import org.springframework.data.geo.Circle; import org.springframework.data.geo.Circle;
import org.springframework.data.geo.GeoResults; import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Metrics; import org.springframework.data.geo.Metrics;
import org.springframework.data.geo.Point; import org.springframework.data.geo.Point;
import org.springframework.data.geo.Polygon; import org.springframework.data.geo.Polygon;
@ -113,8 +111,8 @@ public abstract class AbstractGeoSpatialTests {
GeoResults<Venue> result = template.geoNear(geoNear, Venue.class); GeoResults<Venue> result = template.geoNear(geoNear, Venue.class);
assertThat(result.getContent().size(), is(not(0))); assertThat(result.getContent()).isNotEmpty();
assertThat(result.getAverageDistance().getMetric(), is((Metric) Metrics.KILOMETERS)); assertThat(result.getAverageDistance().getMetric()).isEqualTo(Metrics.KILOMETERS);
} }
@Test @Test
@ -122,7 +120,7 @@ public abstract class AbstractGeoSpatialTests {
Circle circle = new Circle(-73.99171, 40.738868, 0.01); Circle circle = new Circle(-73.99171, 40.738868, 0.01);
List<Venue> venues = template.find(query(where("location").within(circle)), Venue.class); List<Venue> venues = template.find(query(where("location").within(circle)), Venue.class);
assertThat(venues.size(), is(7)); assertThat(venues).hasSize(7);
} }
@Test @Test
@ -130,7 +128,7 @@ public abstract class AbstractGeoSpatialTests {
Circle circle = new Circle(-73.99171, 40.738868, 0.003712240453784); Circle circle = new Circle(-73.99171, 40.738868, 0.003712240453784);
List<Venue> venues = template.find(query(where("location").withinSphere(circle)), Venue.class); List<Venue> venues = template.find(query(where("location").withinSphere(circle)), Venue.class);
assertThat(venues.size(), is(11)); assertThat(venues).hasSize(11);
} }
@Test @Test
@ -138,7 +136,7 @@ public abstract class AbstractGeoSpatialTests {
Box box = new Box(new Point(-73.99756, 40.73083), new Point(-73.988135, 40.741404)); Box box = new Box(new Point(-73.99756, 40.73083), new Point(-73.988135, 40.741404));
List<Venue> venues = template.find(query(where("location").within(box)), Venue.class); List<Venue> venues = template.find(query(where("location").within(box)), Venue.class);
assertThat(venues.size(), is(4)); assertThat(venues).hasSize(4);
} }
@Test @Test
@ -152,15 +150,16 @@ public abstract class AbstractGeoSpatialTests {
Polygon polygon = new Polygon(first, second, third, fourth); Polygon polygon = new Polygon(first, second, third, fourth);
List<Venue> venues = template.find(query(where("location").within(polygon)), Venue.class); List<Venue> venues = template.find(query(where("location").within(polygon)), Venue.class);
assertThat(venues.size(), is(4)); assertThat(venues).hasSize(4);
} }
@Test @Test
public void nearSphere() { public void nearSphere() {
Point point = new Point(-73.99171, 40.738868); Point point = new Point(-73.99171, 40.738868);
Query query = query(where("location").nearSphere(point).maxDistance(0.003712240453784)); Query query = query(where("location").nearSphere(point).maxDistance(0.003712240453784));
List<Venue> venues = template.find(query, Venue.class); List<Venue> venues = template.find(query, Venue.class);
assertThat(venues.size(), is(11)); assertThat(venues).hasSize(11);
} }
@Test // DATAMONGO-1360 @Test // DATAMONGO-1360

45
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoJsonTests.java

@ -15,8 +15,7 @@
*/ */
package org.springframework.data.mongodb.core.geo; package org.springframework.data.mongodb.core.geo;
import static org.hamcrest.Matchers.*; import static org.assertj.core.api.Assertions.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.core.query.Criteria.*; 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.query.Query.*;
@ -35,7 +34,6 @@ import org.springframework.dao.DataAccessException;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor; import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.geo.GeoResults; import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Metrics; import org.springframework.data.geo.Metrics;
import org.springframework.data.geo.Point; import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration; import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
@ -102,8 +100,8 @@ public class GeoJsonTests {
GeoResults<Venue2DSphere> result = template.geoNear(geoNear, Venue2DSphere.class); GeoResults<Venue2DSphere> result = template.geoNear(geoNear, Venue2DSphere.class);
assertThat(result.getContent().size(), is(not(0))); assertThat(result.getContent()).isNotEmpty();
assertThat(result.getAverageDistance().getMetric(), is((Metric) Metrics.KILOMETERS)); assertThat(result.getAverageDistance().getMetric()).isEqualTo(Metrics.KILOMETERS);
} }
@Test // DATAMONGO-1135 @Test // DATAMONGO-1135
@ -117,7 +115,7 @@ public class GeoJsonTests {
GeoJsonPolygon polygon = new GeoJsonPolygon(first, second, third, fourth, first); GeoJsonPolygon polygon = new GeoJsonPolygon(first, second, third, fourth, first);
List<Venue2DSphere> venues = template.find(query(where("location").within(polygon)), Venue2DSphere.class); List<Venue2DSphere> venues = template.find(query(where("location").within(polygon)), Venue2DSphere.class);
assertThat(venues.size(), is(4)); assertThat(venues).hasSize(4);
} }
@Test // DATAMONGO-1135 @Test // DATAMONGO-1135
@ -127,7 +125,7 @@ public class GeoJsonTests {
Query query = query(where("location").near(point).maxDistance(0.01)); Query query = query(where("location").near(point).maxDistance(0.01));
List<Venue2DSphere> venues = template.find(query, Venue2DSphere.class); List<Venue2DSphere> venues = template.find(query, Venue2DSphere.class);
assertThat(venues.size(), is(1)); assertThat(venues).hasSize(1);
} }
@Test // DATAMONGO-1135 @Test // DATAMONGO-1135
@ -138,7 +136,7 @@ public class GeoJsonTests {
Query query = query(where("location").nearSphere(point).maxDistance(0.003712240453784)); Query query = query(where("location").nearSphere(point).maxDistance(0.003712240453784));
List<Venue2DSphere> venues = template.find(query, Venue2DSphere.class); List<Venue2DSphere> venues = template.find(query, Venue2DSphere.class);
assertThat(venues.size(), is(1)); assertThat(venues).hasSize(1);
} }
@Test // DATAMONGO-1137 @Test // DATAMONGO-1137
@ -153,7 +151,7 @@ public class GeoJsonTests {
DocumentWithPropertyUsingGeoJsonType result = template.findOne(query(where("id").is(obj.id)), DocumentWithPropertyUsingGeoJsonType result = template.findOne(query(where("id").is(obj.id)),
DocumentWithPropertyUsingGeoJsonType.class); DocumentWithPropertyUsingGeoJsonType.class);
assertThat(result.geoJsonPoint, equalTo(obj.geoJsonPoint)); assertThat(result.geoJsonPoint).isEqualTo(obj.geoJsonPoint);
} }
@Test // DATAMONGO-1137 @Test // DATAMONGO-1137
@ -169,7 +167,7 @@ public class GeoJsonTests {
DocumentWithPropertyUsingGeoJsonType result = template.findOne(query(where("id").is(obj.id)), DocumentWithPropertyUsingGeoJsonType result = template.findOne(query(where("id").is(obj.id)),
DocumentWithPropertyUsingGeoJsonType.class); DocumentWithPropertyUsingGeoJsonType.class);
assertThat(result.geoJsonPolygon, equalTo(obj.geoJsonPolygon)); assertThat(result.geoJsonPolygon).isEqualTo(obj.geoJsonPolygon);
} }
@Test // DATAMONGO-1137 @Test // DATAMONGO-1137
@ -184,7 +182,7 @@ public class GeoJsonTests {
DocumentWithPropertyUsingGeoJsonType result = template.findOne(query(where("id").is(obj.id)), DocumentWithPropertyUsingGeoJsonType result = template.findOne(query(where("id").is(obj.id)),
DocumentWithPropertyUsingGeoJsonType.class); DocumentWithPropertyUsingGeoJsonType.class);
assertThat(result.geoJsonLineString, equalTo(obj.geoJsonLineString)); assertThat(result.geoJsonLineString).isEqualTo(obj.geoJsonLineString);
} }
@Test // DATAMONGO-1137 @Test // DATAMONGO-1137
@ -201,7 +199,7 @@ public class GeoJsonTests {
DocumentWithPropertyUsingGeoJsonType result = template.findOne(query(where("id").is(obj.id)), DocumentWithPropertyUsingGeoJsonType result = template.findOne(query(where("id").is(obj.id)),
DocumentWithPropertyUsingGeoJsonType.class); DocumentWithPropertyUsingGeoJsonType.class);
assertThat(result.geoJsonMultiLineString, equalTo(obj.geoJsonMultiLineString)); assertThat(result.geoJsonMultiLineString).isEqualTo(obj.geoJsonMultiLineString);
} }
@Test // DATAMONGO-1137 @Test // DATAMONGO-1137
@ -216,7 +214,7 @@ public class GeoJsonTests {
DocumentWithPropertyUsingGeoJsonType result = template.findOne(query(where("id").is(obj.id)), DocumentWithPropertyUsingGeoJsonType result = template.findOne(query(where("id").is(obj.id)),
DocumentWithPropertyUsingGeoJsonType.class); DocumentWithPropertyUsingGeoJsonType.class);
assertThat(result.geoJsonMultiPoint, equalTo(obj.geoJsonMultiPoint)); assertThat(result.geoJsonMultiPoint).isEqualTo(obj.geoJsonMultiPoint);
} }
@Test // DATAMONGO-1137 @Test // DATAMONGO-1137
@ -232,7 +230,7 @@ public class GeoJsonTests {
DocumentWithPropertyUsingGeoJsonType result = template.findOne(query(where("id").is(obj.id)), DocumentWithPropertyUsingGeoJsonType result = template.findOne(query(where("id").is(obj.id)),
DocumentWithPropertyUsingGeoJsonType.class); DocumentWithPropertyUsingGeoJsonType.class);
assertThat(result.geoJsonMultiPolygon, equalTo(obj.geoJsonMultiPolygon)); assertThat(result.geoJsonMultiPolygon).isEqualTo(obj.geoJsonMultiPolygon);
} }
@Test // DATAMONGO-1137 @Test // DATAMONGO-1137
@ -248,7 +246,7 @@ public class GeoJsonTests {
DocumentWithPropertyUsingGeoJsonType result = template.findOne(query(where("id").is(obj.id)), DocumentWithPropertyUsingGeoJsonType result = template.findOne(query(where("id").is(obj.id)),
DocumentWithPropertyUsingGeoJsonType.class); DocumentWithPropertyUsingGeoJsonType.class);
assertThat(result.geoJsonGeometryCollection, equalTo(obj.geoJsonGeometryCollection)); assertThat(result.geoJsonGeometryCollection).isEqualTo(obj.geoJsonGeometryCollection);
} }
@Test // DATAMONGO-1110 @Test // DATAMONGO-1110
@ -258,7 +256,7 @@ public class GeoJsonTests {
List<Venue2DSphere> venues = template.find(query(where("location").near(point).minDistance(0.01)), List<Venue2DSphere> venues = template.find(query(where("location").near(point).minDistance(0.01)),
Venue2DSphere.class); Venue2DSphere.class);
assertThat(venues.size(), is(11)); assertThat(venues).hasSize(11);
} }
@Test // DATAMONGO-1110 @Test // DATAMONGO-1110
@ -268,7 +266,7 @@ public class GeoJsonTests {
List<Venue2DSphere> venues = template.find(query(where("location").nearSphere(point).minDistance(0.01)), List<Venue2DSphere> venues = template.find(query(where("location").nearSphere(point).minDistance(0.01)),
Venue2DSphere.class); Venue2DSphere.class);
assertThat(venues.size(), is(11)); assertThat(venues).hasSize(11);
} }
@Test // DATAMONGO-1135 @Test // DATAMONGO-1135
@ -278,7 +276,7 @@ public class GeoJsonTests {
Query query = query(where("location").near(point).minDistance(0.01).maxDistance(100)); Query query = query(where("location").near(point).minDistance(0.01).maxDistance(100));
List<Venue2DSphere> venues = template.find(query, Venue2DSphere.class); List<Venue2DSphere> venues = template.find(query, Venue2DSphere.class);
assertThat(venues.size(), is(2)); assertThat(venues).hasSize(2);
} }
@Test // DATAMONGO-1453 @Test // DATAMONGO-1453
@ -306,7 +304,7 @@ public class GeoJsonTests {
}); });
assertThat(template.findOne(query(where("id").is("datamongo-1453")), assertThat(template.findOne(query(where("id").is("datamongo-1453")),
DocumentWithPropertyUsingGeoJsonType.class).geoJsonPoint, is(equalTo(new GeoJsonPoint(0D, 0D)))); DocumentWithPropertyUsingGeoJsonType.class).geoJsonPoint).isEqualTo(new GeoJsonPoint(0D, 0D));
} }
@Test // DATAMONGO-1453 @Test // DATAMONGO-1453
@ -335,10 +333,9 @@ public class GeoJsonTests {
} }
}); });
assertThat( assertThat(template.findOne(query(where("id").is("datamongo-1453")),
template.findOne(query(where("id").is("datamongo-1453")), DocumentWithPropertyUsingGeoJsonType.class).geoJsonLineString)
DocumentWithPropertyUsingGeoJsonType.class).geoJsonLineString, .isEqualTo(new GeoJsonLineString(new Point(0D, 0D), new Point(1, 1)));
is(equalTo(new GeoJsonLineString(new Point(0D, 0D), new Point(1, 1)))));
} }
@Test // DATAMONGO-1466 @Test // DATAMONGO-1466
@ -359,7 +356,7 @@ public class GeoJsonTests {
OpenGeoJson target = template.findOne(query(where("id").is(source.id)), OpenGeoJson.class); OpenGeoJson target = template.findOne(query(where("id").is(source.id)), OpenGeoJson.class);
assertThat(target.shape, is(equalTo(source.shape))); assertThat(target.shape).isEqualTo(source.shape);
} }
private void addVenues() { private void addVenues() {

17
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoSpatialIndexTests.java

@ -15,8 +15,7 @@
*/ */
package org.springframework.data.mongodb.core.geo; package org.springframework.data.mongodb.core.geo;
import static org.hamcrest.Matchers.*; import static org.assertj.core.api.Assertions.*;
import static org.junit.Assert.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -29,12 +28,12 @@ import org.springframework.dao.DataAccessException;
import org.springframework.data.geo.Point; import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.config.AbstractIntegrationTests; import org.springframework.data.mongodb.config.AbstractIntegrationTests;
import org.springframework.data.mongodb.core.CollectionCallback; import org.springframework.data.mongodb.core.CollectionCallback;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.WriteResultChecking; import org.springframework.data.mongodb.core.WriteResultChecking;
import org.springframework.data.mongodb.core.index.GeoSpatialIndexType; import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;
import org.springframework.data.mongodb.core.index.GeoSpatialIndexed; import org.springframework.data.mongodb.core.index.GeoSpatialIndexed;
import org.springframework.data.mongodb.core.index.IndexInfo; import org.springframework.data.mongodb.core.index.IndexInfo;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
import com.mongodb.MongoException; import com.mongodb.MongoException;
@ -65,7 +64,7 @@ public class GeoSpatialIndexTests extends AbstractIntegrationTests {
try { try {
template.save(new GeoSpatialEntity2D(45.2, 4.6)); template.save(new GeoSpatialEntity2D(45.2, 4.6));
assertThat(hasIndexOfType(GeoSpatialEntity2D.class, "2d"), is(true)); assertThat(hasIndexOfType(GeoSpatialEntity2D.class, "2d")).isTrue();
} finally { } finally {
template.dropCollection(GeoSpatialEntity2D.class); template.dropCollection(GeoSpatialEntity2D.class);
} }
@ -76,7 +75,7 @@ public class GeoSpatialIndexTests extends AbstractIntegrationTests {
try { try {
template.save(new GeoSpatialEntity2DSphere(45.2, 4.6)); template.save(new GeoSpatialEntity2DSphere(45.2, 4.6));
assertThat(hasIndexOfType(GeoSpatialEntity2DSphere.class, "2dsphere"), is(true)); assertThat(hasIndexOfType(GeoSpatialEntity2DSphere.class, "2dsphere")).isTrue();
} finally { } finally {
template.dropCollection(GeoSpatialEntity2DSphere.class); template.dropCollection(GeoSpatialEntity2DSphere.class);
} }
@ -87,7 +86,7 @@ public class GeoSpatialIndexTests extends AbstractIntegrationTests {
try { try {
template.save(new GeoSpatialEntityHaystack(45.2, 4.6, "Paris")); template.save(new GeoSpatialEntityHaystack(45.2, 4.6, "Paris"));
assertThat(hasIndexOfType(GeoSpatialEntityHaystack.class, "geoHaystack"), is(true)); assertThat(hasIndexOfType(GeoSpatialEntityHaystack.class, "geoHaystack")).isTrue();
} finally { } finally {
template.dropCollection(GeoSpatialEntityHaystack.class); template.dropCollection(GeoSpatialEntityHaystack.class);
} }
@ -104,9 +103,9 @@ public class GeoSpatialIndexTests extends AbstractIntegrationTests {
IndexOperations indexOps = template.indexOps(GeoSpatialEntity2dWithGeneratedIndex.class); IndexOperations indexOps = template.indexOps(GeoSpatialEntity2dWithGeneratedIndex.class);
List<IndexInfo> indexInfo = indexOps.getIndexInfo(); List<IndexInfo> indexInfo = indexOps.getIndexInfo();
assertThat(indexInfo, hasSize(2)); assertThat(indexInfo).hasSize(2);
assertThat(indexInfo.get(1), is(notNullValue())); assertThat(indexInfo.get(1)).isNotNull();
assertThat(indexInfo.get(1).getName(), is("location_2d")); assertThat(indexInfo.get(1).getName()).isEqualTo("location_2d");
} finally { } finally {
template.dropCollection(GeoSpatialEntity2D.class); template.dropCollection(GeoSpatialEntity2D.class);

19
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/index/TextIndexTests.java

@ -15,8 +15,7 @@
*/ */
package org.springframework.data.mongodb.core.index; package org.springframework.data.mongodb.core.index;
import static org.hamcrest.Matchers.*; import static org.assertj.core.api.Assertions.*;
import static org.junit.Assert.*;
import java.util.List; import java.util.List;
@ -56,20 +55,18 @@ public class TextIndexTests extends AbstractIntegrationTests {
List<IndexInfo> indexInfos = indexOps.getIndexInfo(); List<IndexInfo> indexInfos = indexOps.getIndexInfo();
assertThat(indexInfos.size(), is(2)); assertThat(indexInfos.size()).isEqualTo(2);
List<IndexField> fields = indexInfos.get(0).getIndexFields(); List<IndexField> fields = indexInfos.get(0).getIndexFields();
assertThat(fields.size(), is(1)); assertThat(fields).containsExactly(IndexField.create("_id", Direction.ASC));
assertThat(fields, hasItem(IndexField.create("_id", Direction.ASC)));
IndexInfo textIndexInfo = indexInfos.get(1); IndexInfo textIndexInfo = indexInfos.get(1);
List<IndexField> textIndexFields = textIndexInfo.getIndexFields(); List<IndexField> textIndexFields = textIndexInfo.getIndexFields();
assertThat(textIndexFields.size(), is(4)); assertThat(textIndexFields).hasSize(4).contains(IndexField.text("textIndexedPropertyWithDefaultWeight", 1F),
assertThat(textIndexFields, hasItem(IndexField.text("textIndexedPropertyWithDefaultWeight", 1F))); IndexField.text("textIndexedPropertyWithWeight", 5F),
assertThat(textIndexFields, hasItem(IndexField.text("textIndexedPropertyWithWeight", 5F))); IndexField.text("nestedDocument.textIndexedPropertyInNestedDocument", 1F),
assertThat(textIndexFields, hasItem(IndexField.text("nestedDocument.textIndexedPropertyInNestedDocument", 1F))); IndexField.create("_ftsx", Direction.ASC));
assertThat(textIndexFields, hasItem(IndexField.create("_ftsx", Direction.ASC))); assertThat(textIndexInfo.getLanguage()).isEqualTo("spanish");
assertThat(textIndexInfo.getLanguage(), is("spanish"));
} }
@Document(language = "spanish") @Document(language = "spanish")

6
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/GeoIndexedTests.java

@ -15,7 +15,7 @@
*/ */
package org.springframework.data.mongodb.core.mapping; package org.springframework.data.mongodb.core.mapping;
import static org.junit.Assert.*; import static org.assertj.core.api.Assertions.*;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.ArrayList; import java.util.ArrayList;
@ -42,6 +42,7 @@ import com.mongodb.client.MongoDatabase;
/** /**
* @author Jon Brisbin * @author Jon Brisbin
* @author Oliver Gierke * @author Oliver Gierke
* @author Christoph Strobl
*/ */
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = GeoIndexedAppConfig.class) @ContextConfiguration(classes = GeoIndexedAppConfig.class)
@ -75,6 +76,7 @@ public class GeoIndexedTests {
@Test @Test
public void testGeoLocation() { public void testGeoLocation() {
GeoLocation geo = new GeoLocation(new double[] { 40.714346, -74.005966 }); GeoLocation geo = new GeoLocation(new double[] { 40.714346, -74.005966 });
template.insert(geo); template.insert(geo);
@ -93,6 +95,6 @@ public class GeoIndexedTests {
} }
}); });
assertTrue(hasIndex); assertThat(hasIndex).isTrue();
} }
} }

131
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/QueryTests.java

@ -15,18 +15,13 @@
*/ */
package org.springframework.data.mongodb.core.query; package org.springframework.data.mongodb.core.query;
import static org.hamcrest.CoreMatchers.*; import static org.assertj.core.api.Assertions.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.core.query.Criteria.*; 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.query.Query.*;
import java.util.Arrays;
import org.bson.Document; import org.bson.Document;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.InvalidMongoDbApiUsageException; import org.springframework.data.mongodb.InvalidMongoDbApiUsageException;
@ -44,41 +39,40 @@ import org.springframework.data.mongodb.core.SpecialDoc;
*/ */
public class QueryTests { public class QueryTests {
@Rule public ExpectedException exception = ExpectedException.none();
@Test @Test
public void testSimpleQuery() { public void testSimpleQuery() {
Query q = new Query(where("name").is("Thomas").and("age").lt(80)); Query q = new Query(where("name").is("Thomas").and("age").lt(80));
Document expected = Document.parse("{ \"name\" : \"Thomas\" , \"age\" : { \"$lt\" : 80}}"); assertThat(q.getQueryObject()).isEqualTo(Document.parse("{ \"name\" : \"Thomas\" , \"age\" : { \"$lt\" : 80}}"));
Assert.assertEquals(expected, q.getQueryObject());
} }
@Test @Test
public void testQueryWithNot() { public void testQueryWithNot() {
Query q = new Query(where("name").is("Thomas").and("age").not().mod(10, 0)); Query q = new Query(where("name").is("Thomas").and("age").not().mod(10, 0));
Document expected = Document.parse("{ \"name\" : \"Thomas\" , \"age\" : { \"$not\" : { \"$mod\" : [ 10 , 0]}}}"); assertThat(q.getQueryObject())
Assert.assertEquals(expected, q.getQueryObject()); .isEqualTo(Document.parse("{ \"name\" : \"Thomas\" , \"age\" : { \"$not\" : { \"$mod\" : [ 10 , 0]}}}"));
} }
@Test @Test
public void testInvalidQueryWithNotIs() { public void testInvalidQueryWithNotIs() {
try {
new Query(where("name").not().is("Thomas")); assertThatExceptionOfType(InvalidMongoDbApiUsageException.class)
Assert.fail("This should have caused an InvalidDocumentStoreApiUsageException"); .isThrownBy(() -> new Query(where("name").not().is("Thomas")));
} catch (InvalidMongoDbApiUsageException e) {}
} }
@Test @Test
public void testOrQuery() { public void testOrQuery() {
Query q = new Query(new Criteria().orOperator(where("name").is("Sven").and("age").lt(50), where("age").lt(50), Query q = new Query(new Criteria().orOperator(where("name").is("Sven").and("age").lt(50), where("age").lt(50),
where("name").is("Thomas"))); where("name").is("Thomas")));
Document expected = Document.parse( assertThat(q.getQueryObject()).isEqualTo(Document.parse(
"{ \"$or\" : [ { \"name\" : \"Sven\" , \"age\" : { \"$lt\" : 50}} , { \"age\" : { \"$lt\" : 50}} , { \"name\" : \"Thomas\"}]}"); "{ \"$or\" : [ { \"name\" : \"Sven\" , \"age\" : { \"$lt\" : 50}} , { \"age\" : { \"$lt\" : 50}} , { \"name\" : \"Thomas\"}]}"));
Assert.assertEquals(expected, q.getQueryObject());
} }
@Test @Test
public void testAndQuery() { public void testAndQuery() {
Query q = new Query(new Criteria().andOperator(where("name").is("Sven"), where("age").lt(50))); Query q = new Query(new Criteria().andOperator(where("name").is("Sven"), where("age").lt(50)));
Document expected = Document.parse("{ \"$and\" : [ { \"name\" : \"Sven\"} , { \"age\" : { \"$lt\" : 50}}]}"); Document expected = Document.parse("{ \"$and\" : [ { \"name\" : \"Sven\"} , { \"age\" : { \"$lt\" : 50}}]}");
Assert.assertEquals(expected, q.getQueryObject()); Assert.assertEquals(expected, q.getQueryObject());
@ -86,33 +80,35 @@ public class QueryTests {
@Test @Test
public void testNorQuery() { public void testNorQuery() {
Query q = new Query( Query q = new Query(
new Criteria().norOperator(where("name").is("Sven"), where("age").lt(50), where("name").is("Thomas"))); new Criteria().norOperator(where("name").is("Sven"), where("age").lt(50), where("name").is("Thomas")));
Document expected = Document assertThat(q.getQueryObject()).isEqualTo(Document
.parse("{ \"$nor\" : [ { \"name\" : \"Sven\"} , { \"age\" : { \"$lt\" : 50}} , { \"name\" : \"Thomas\"}]}"); .parse("{ \"$nor\" : [ { \"name\" : \"Sven\"} , { \"age\" : { \"$lt\" : 50}} , { \"name\" : \"Thomas\"}]}"));
Assert.assertEquals(expected, q.getQueryObject());
} }
@Test @Test
public void testQueryWithLimit() { public void testQueryWithLimit() {
Query q = new Query(where("name").gte("M").lte("T").and("age").not().gt(22)); Query q = new Query(where("name").gte("M").lte("T").and("age").not().gt(22));
q.limit(50); q.limit(50);
Document expected = Document
.parse("{ \"name\" : { \"$gte\" : \"M\" , \"$lte\" : \"T\"} , \"age\" : { \"$not\" : { \"$gt\" : 22}}}"); assertThat(q.getQueryObject()).isEqualTo(Document
Assert.assertEquals(expected, q.getQueryObject()); .parse("{ \"name\" : { \"$gte\" : \"M\" , \"$lte\" : \"T\"} , \"age\" : { \"$not\" : { \"$gt\" : 22}}}"));
Assert.assertEquals(50, q.getLimit()); Assert.assertEquals(50, q.getLimit());
} }
@Test @Test
public void testQueryWithFieldsAndSlice() { public void testQueryWithFieldsAndSlice() {
Query q = new Query(where("name").gte("M").lte("T").and("age").not().gt(22)); Query q = new Query(where("name").gte("M").lte("T").and("age").not().gt(22));
q.fields().exclude("address").include("name").slice("orders", 10); q.fields().exclude("address").include("name").slice("orders", 10);
Document expected = Document assertThat(q.getQueryObject()).isEqualTo(Document
.parse("{ \"name\" : { \"$gte\" : \"M\" , \"$lte\" : \"T\"} , \"age\" : { \"$not\" : { \"$gt\" : 22}}}"); .parse("{ \"name\" : { \"$gte\" : \"M\" , \"$lte\" : \"T\"} , \"age\" : { \"$not\" : { \"$gt\" : 22}}}"));
Assert.assertEquals(expected, q.getQueryObject());
Document expectedFields = Document.parse("{ \"address\" : 0 , \"name\" : 1 , \"orders\" : { \"$slice\" : 10}}"); assertThat(q.getFieldsObject())
Assert.assertEquals(expectedFields, q.getFieldsObject()); .isEqualTo(Document.parse("{ \"address\" : 0 , \"name\" : 1 , \"orders\" : { \"$slice\" : 10}}"));
} }
@Test // DATAMONGO-652 @Test // DATAMONGO-652
@ -121,87 +117,87 @@ public class QueryTests {
Query query = query(where("name").gte("M").lte("T").and("age").not().gt(22)); Query query = query(where("name").gte("M").lte("T").and("age").not().gt(22));
query.fields().elemMatch("products", where("name").is("milk")).position("comments", 2); query.fields().elemMatch("products", where("name").is("milk")).position("comments", 2);
Document expected = Document assertThat(query.getQueryObject()).isEqualTo(Document
.parse("{ \"name\" : { \"$gte\" : \"M\" , \"$lte\" : \"T\"} , \"age\" : { \"$not\" : { \"$gt\" : 22}}}"); .parse("{ \"name\" : { \"$gte\" : \"M\" , \"$lte\" : \"T\"} , \"age\" : { \"$not\" : { \"$gt\" : 22}}}"));
assertThat(query.getQueryObject(), is(expected)); assertThat(query.getFieldsObject())
Document expectedFields = Document .isEqualTo(Document.parse("{ \"products\" : { \"$elemMatch\" : { \"name\" : \"milk\"}} , \"comments.$\" : 2}"));
.parse("{ \"products\" : { \"$elemMatch\" : { \"name\" : \"milk\"}} , \"comments.$\" : 2}");
assertThat(query.getFieldsObject(), is(expectedFields));
} }
@Test @Test
public void testSimpleQueryWithChainedCriteria() { public void testSimpleQueryWithChainedCriteria() {
Query q = new Query(where("name").is("Thomas").and("age").lt(80)); Query q = new Query(where("name").is("Thomas").and("age").lt(80));
Document expected = Document.parse("{ \"name\" : \"Thomas\" , \"age\" : { \"$lt\" : 80}}"); assertThat(q.getQueryObject()).isEqualTo(Document.parse("{ \"name\" : \"Thomas\" , \"age\" : { \"$lt\" : 80}}"));
Assert.assertEquals(expected, q.getQueryObject());
} }
@Test @Test
public void testComplexQueryWithMultipleChainedCriteria() { public void testComplexQueryWithMultipleChainedCriteria() {
Query q = new Query( Query q = new Query(
where("name").regex("^T.*").and("age").gt(20).lt(80).and("city").in("Stockholm", "London", "New York")); where("name").regex("^T.*").and("age").gt(20).lt(80).and("city").in("Stockholm", "London", "New York"));
Document expected = Document assertThat(q.getQueryObject().toJson()).isEqualTo(Document.parse(
.parse("{ \"name\" : { \"$regex\" : \"^T.*\", \"$options\" : \"\" } , \"age\" : { \"$gt\" : 20 , \"$lt\" : 80} , " "{ \"name\" : { \"$regex\" : \"^T.*\", \"$options\" : \"\" } , \"age\" : { \"$gt\" : 20 , \"$lt\" : 80} , "
+ "\"city\" : { \"$in\" : [ \"Stockholm\" , \"London\" , \"New York\"]}}"); + "\"city\" : { \"$in\" : [ \"Stockholm\" , \"London\" , \"New York\"]}}")
.toJson());
Assert.assertEquals(expected.toJson(), q.getQueryObject().toJson());
} }
@Test @Test
public void testAddCriteriaWithComplexQueryWithMultipleChainedCriteria() { public void testAddCriteriaWithComplexQueryWithMultipleChainedCriteria() {
Query q1 = new Query( Query q1 = new Query(
where("name").regex("^T.*").and("age").gt(20).lt(80).and("city").in("Stockholm", "London", "New York")); where("name").regex("^T.*").and("age").gt(20).lt(80).and("city").in("Stockholm", "London", "New York"));
Query q2 = new Query(where("name").regex("^T.*").and("age").gt(20).lt(80)) Query q2 = new Query(where("name").regex("^T.*").and("age").gt(20).lt(80))
.addCriteria(where("city").in("Stockholm", "London", "New York")); .addCriteria(where("city").in("Stockholm", "London", "New York"));
Assert.assertEquals(q1.getQueryObject().toString(), q2.getQueryObject().toString());
assertThat(q1.getQueryObject().toString()).isEqualTo(q2.getQueryObject().toString());
Query q3 = new Query(where("name").regex("^T.*")).addCriteria(where("age").gt(20).lt(80)) Query q3 = new Query(where("name").regex("^T.*")).addCriteria(where("age").gt(20).lt(80))
.addCriteria(where("city").in("Stockholm", "London", "New York")); .addCriteria(where("city").in("Stockholm", "London", "New York"));
Assert.assertEquals(q1.getQueryObject().toString(), q3.getQueryObject().toString()); assertThat(q1.getQueryObject().toString()).isEqualTo(q3.getQueryObject().toString());
} }
@Test @Test
public void testQueryWithElemMatch() { public void testQueryWithElemMatch() {
Query q = new Query(where("openingHours").elemMatch(where("dayOfWeek").is("Monday").and("open").lte("1800"))); Query q = new Query(where("openingHours").elemMatch(where("dayOfWeek").is("Monday").and("open").lte("1800")));
Document expected = Document.parse( assertThat(q.getQueryObject()).isEqualTo(Document.parse(
"{ \"openingHours\" : { \"$elemMatch\" : { \"dayOfWeek\" : \"Monday\" , \"open\" : { \"$lte\" : \"1800\"}}}}"); "{ \"openingHours\" : { \"$elemMatch\" : { \"dayOfWeek\" : \"Monday\" , \"open\" : { \"$lte\" : \"1800\"}}}}"));
Assert.assertEquals(expected, q.getQueryObject());
} }
@Test @Test
public void testQueryWithIn() { public void testQueryWithIn() {
Query q = new Query(where("state").in("NY", "NJ", "PA")); Query q = new Query(where("state").in("NY", "NJ", "PA"));
Document expected = Document.parse("{ \"state\" : { \"$in\" : [ \"NY\" , \"NJ\" , \"PA\"]}}"); assertThat(q.getQueryObject()).isEqualTo(Document.parse("{ \"state\" : { \"$in\" : [ \"NY\" , \"NJ\" , \"PA\"]}}"));
Assert.assertEquals(expected, q.getQueryObject());
} }
@Test @Test
public void testQueryWithRegex() { public void testQueryWithRegex() {
Query q = new Query(where("name").regex("b.*")); Query q = new Query(where("name").regex("b.*"));
Document expected = Document.parse("{ \"name\" : { \"$regex\" : \"b.*\", \"$options\" : \"\" }}"); assertThat(q.getQueryObject().toJson())
Assert.assertEquals(expected.toJson(), q.getQueryObject().toJson()); .isEqualTo(Document.parse("{ \"name\" : { \"$regex\" : \"b.*\", \"$options\" : \"\" }}").toJson());
} }
@Test @Test
public void testQueryWithRegexAndOption() { public void testQueryWithRegexAndOption() {
Query q = new Query(where("name").regex("b.*", "i")); Query q = new Query(where("name").regex("b.*", "i"));
Document expected = Document.parse("{ \"name\" : { \"$regex\" : \"b.*\" , \"$options\" : \"i\"}}"); assertThat(q.getQueryObject().toJson())
Assert.assertEquals(expected.toJson(), q.getQueryObject().toJson()); .isEqualTo(Document.parse("{ \"name\" : { \"$regex\" : \"b.*\" , \"$options\" : \"i\"}}").toJson());
} }
@Test // DATAMONGO-538 @Test // DATAMONGO-538
public void addsSortCorrectly() { public void addsSortCorrectly() {
Query query = new Query().with(Sort.by(Direction.DESC, "foo")); Query query = new Query().with(Sort.by(Direction.DESC, "foo"));
assertThat(query.getSortObject(), is(Document.parse("{ \"foo\" : -1}"))); assertThat(query.getSortObject()).isEqualTo(Document.parse("{ \"foo\" : -1}"));
} }
@Test @Test
public void rejectsOrderWithIgnoreCase() { public void rejectsOrderWithIgnoreCase() {
exception.expect(IllegalArgumentException.class); assertThatExceptionOfType(IllegalArgumentException.class)
exception.expectMessage("foo"); .isThrownBy(() -> new Query().with(Sort.by(new Sort.Order("foo").ignoreCase())));
new Query().with(Sort.by(new Sort.Order("foo").ignoreCase()));
} }
@Test // DATAMONGO-709, DATAMONGO-1735, // DATAMONGO-2198 @Test // DATAMONGO-709, DATAMONGO-1735, // DATAMONGO-2198
@ -210,21 +206,20 @@ public class QueryTests {
Query query = new Query(where("name").is("foo")).restrict(SpecialDoc.class); Query query = new Query(where("name").is("foo")).restrict(SpecialDoc.class);
assertThat(query.getRestrictedTypes(), is(notNullValue())); assertThat(query.getRestrictedTypes()).containsExactly(SpecialDoc.class);
assertThat(query.getRestrictedTypes().size(), is(1));
assertThat(query.getRestrictedTypes(), hasItems(Arrays.asList(SpecialDoc.class).toArray(new Class<?>[0])));
} }
@Test // DATAMONGO-1421 @Test // DATAMONGO-1421
public void addCriteriaForSamePropertyMultipleTimesShouldThrowAndSafelySerializeErrorMessage() { public void addCriteriaForSamePropertyMultipleTimesShouldThrowAndSafelySerializeErrorMessage() {
exception.expect(InvalidMongoDbApiUsageException.class); assertThatExceptionOfType(InvalidMongoDbApiUsageException.class).isThrownBy(() -> {
exception.expectMessage("second 'value' criteria");
exception.expectMessage("already contains '{ \"value\" : { \"$java\" : VAL_1 } }'"); Query query = new Query();
query.addCriteria(where("value").is(EnumType.VAL_1));
query.addCriteria(where("value").is(EnumType.VAL_2));
}).withMessageContaining("second 'value' criteria")
.withMessageContaining("already contains '{ \"value\" : { \"$java\" : VAL_1 } }'");
Query query = new Query();
query.addCriteria(where("value").is(EnumType.VAL_1));
query.addCriteria(where("value").is(EnumType.VAL_2));
} }
enum EnumType { enum EnumType {

Loading…
Cancel
Save