DATAMONGO-2321 - Migrate tests to AssertJ.

This commit is contained in:
Mark Paluch
2019-07-11 11:07:15 +02:00
parent 394efa8b82
commit fad18341fa
126 changed files with 2502 additions and 3158 deletions

View File

@@ -15,9 +15,8 @@
*/
package org.springframework.data.mongodb;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import javax.transaction.Status;
@@ -29,6 +28,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.jta.JtaTransactionManager;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
@@ -70,12 +70,12 @@ public class MongoDatabaseUtilsUnitTests {
@After
public void verifyTransactionSynchronizationManagerState() {
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
assertNull(TransactionSynchronizationManager.getCurrentTransactionName());
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
assertNull(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel());
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue();
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse();
assertThat(TransactionSynchronizationManager.getCurrentTransactionName()).isNull();
assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse();
assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()).isNull();
assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
}
@Test // DATAMONGO-2130

View File

@@ -16,7 +16,6 @@
package org.springframework.data.mongodb;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.After;
@@ -25,6 +24,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
@@ -72,8 +72,8 @@ public class MongoTransactionManagerUnitTests {
@After
public void verifyTransactionSynchronizationManager() {
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue();
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse();
}
@Test // DATAMONGO-1920

View File

@@ -15,7 +15,7 @@
*/
package org.springframework.data.mongodb;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import reactor.core.publisher.Mono;
@@ -27,6 +27,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.reactive.TransactionalOperator;
@@ -72,8 +73,8 @@ public class ReactiveMongoTransactionManagerUnitTests {
@After
public void verifyTransactionSynchronizationManager() {
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue();
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse();
}
@Test // DATAMONGO-2265

View File

@@ -15,13 +15,13 @@
*/
package org.springframework.data.mongodb.config;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.test.util.Assertions.*;
import org.bson.Document;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.DataAccessException;
@@ -68,7 +68,7 @@ public abstract class AbstractIntegrationTests {
@Override
public Void doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
collection.deleteMany(new Document());
assertThat(collection.find().iterator().hasNext(), is(false));
assertThat(collection.find().iterator().hasNext()).isFalse();
return null;
}
});

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.config;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import example.first.First;
import example.second.Second;
@@ -29,6 +28,7 @@ import java.util.Set;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
@@ -61,9 +61,9 @@ public class AbstractMongoConfigurationUnitTests {
public void usesConfigClassPackageAsBaseMappingPackage() throws ClassNotFoundException {
AbstractMongoConfiguration configuration = new SampleMongoConfiguration();
assertThat(configuration.getMappingBasePackage(), is(SampleMongoConfiguration.class.getPackage().getName()));
assertThat(configuration.getInitialEntitySet(), hasSize(2));
assertThat(configuration.getInitialEntitySet(), hasItem(Entity.class));
assertThat(configuration.getMappingBasePackage()).isEqualTo(SampleMongoConfiguration.class.getPackage().getName());
assertThat(configuration.getInitialEntitySet()).hasSize(2);
assertThat(configuration.getInitialEntitySet()).contains(Entity.class);
}
@Test // DATAMONGO-496
@@ -83,7 +83,7 @@ public class AbstractMongoConfigurationUnitTests {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(SampleMongoConfiguration.class);
assertThat(context.getBean(MongoDbFactory.class), is(notNullValue()));
assertThat(context.getBean(MongoDbFactory.class)).isNotNull();
exception.expect(NoSuchBeanDefinitionException.class);
context.getBean(MongoClient.class);
@@ -96,9 +96,9 @@ public class AbstractMongoConfigurationUnitTests {
SampleMongoConfiguration configuration = new SampleMongoConfiguration();
MongoMappingContext context = configuration.mongoMappingContext();
assertThat(context.getPersistentEntities(), is(emptyIterable()));
assertThat(context.getPersistentEntities()).isEmpty();
context.initialize();
assertThat(context.getPersistentEntities(), is(not(emptyIterable())));
assertThat(context.getPersistentEntities()).isNotEmpty();
}
@Test // DATAMONGO-717
@@ -110,7 +110,7 @@ public class AbstractMongoConfigurationUnitTests {
EvaluationContextProvider provider = (EvaluationContextProvider) ReflectionTestUtils.getField(entity,
"evaluationContextProvider");
assertThat(provider, is(instanceOf(ExtensionAwareEvaluationContextProvider.class)));
assertThat(provider).isInstanceOf(ExtensionAwareEvaluationContextProvider.class);
context.close();
}
@@ -121,8 +121,8 @@ public class AbstractMongoConfigurationUnitTests {
MongoTypeMapper typeMapper = context.getBean(CustomMongoTypeMapper.class);
MappingMongoConverter mmc = context.getBean(MappingMongoConverter.class);
assertThat(mmc, is(notNullValue()));
assertThat(mmc.getTypeMapper(), is(typeMapper));
assertThat(mmc).isNotNull();
assertThat(mmc.getTypeMapper()).isEqualTo(typeMapper);
context.close();
}
@@ -133,8 +133,8 @@ public class AbstractMongoConfigurationUnitTests {
ConfigurationWithMultipleBasePackages config = new ConfigurationWithMultipleBasePackages();
Set<Class<?>> entities = config.getInitialEntitySet();
assertThat(entities, hasSize(2));
assertThat(entities, hasItems(First.class, Second.class));
assertThat(entities).hasSize(2);
assertThat(entities).contains(First.class, Second.class);
}
private static void assertScanningDisabled(final String value) throws ClassNotFoundException {
@@ -146,8 +146,8 @@ public class AbstractMongoConfigurationUnitTests {
}
};
assertThat(configuration.getMappingBasePackages(), hasItem(value));
assertThat(configuration.getInitialEntitySet(), hasSize(0));
assertThat(configuration.getMappingBasePackages()).contains(value);
assertThat(configuration.getInitialEntitySet()).hasSize(0);
}
@Configuration

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.config;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import example.first.First;
import example.second.Second;
@@ -29,6 +28,7 @@ import java.util.Set;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
@@ -61,9 +61,9 @@ public class AbstractReactiveMongoConfigurationUnitTests {
public void usesConfigClassPackageAsBaseMappingPackage() throws ClassNotFoundException {
AbstractReactiveMongoConfiguration configuration = new SampleMongoConfiguration();
assertThat(configuration.getMappingBasePackages(), hasItem(SampleMongoConfiguration.class.getPackage().getName()));
assertThat(configuration.getInitialEntitySet(), hasSize(2));
assertThat(configuration.getInitialEntitySet(), hasItem(Entity.class));
assertThat(configuration.getMappingBasePackages()).contains(SampleMongoConfiguration.class.getPackage().getName());
assertThat(configuration.getInitialEntitySet()).hasSize(2);
assertThat(configuration.getInitialEntitySet()).contains(Entity.class);
}
@Test // DATAMONGO-1444
@@ -83,7 +83,7 @@ public class AbstractReactiveMongoConfigurationUnitTests {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(SampleMongoConfiguration.class);
assertThat(context.getBean(SimpleReactiveMongoDatabaseFactory.class), is(notNullValue()));
assertThat(context.getBean(SimpleReactiveMongoDatabaseFactory.class)).isNotNull();
exception.expect(NoSuchBeanDefinitionException.class);
@@ -100,9 +100,9 @@ public class AbstractReactiveMongoConfigurationUnitTests {
SampleMongoConfiguration configuration = new SampleMongoConfiguration();
MongoMappingContext context = configuration.mongoMappingContext();
assertThat(context.getPersistentEntities(), is(emptyIterable()));
assertThat(context.getPersistentEntities()).isEmpty();
context.initialize();
assertThat(context.getPersistentEntities(), is(not(emptyIterable())));
assertThat(context.getPersistentEntities()).isNotEmpty();
}
@Test // DATAMONGO-1444
@@ -114,7 +114,7 @@ public class AbstractReactiveMongoConfigurationUnitTests {
EvaluationContextProvider provider = (EvaluationContextProvider) ReflectionTestUtils.getField(entity,
"evaluationContextProvider");
assertThat(provider, is(instanceOf(ExtensionAwareEvaluationContextProvider.class)));
assertThat(provider).isInstanceOf(ExtensionAwareEvaluationContextProvider.class);
context.close();
}
@@ -125,8 +125,8 @@ public class AbstractReactiveMongoConfigurationUnitTests {
MongoTypeMapper typeMapper = context.getBean(CustomMongoTypeMapper.class);
MappingMongoConverter mmc = context.getBean(MappingMongoConverter.class);
assertThat(mmc, is(notNullValue()));
assertThat(mmc.getTypeMapper(), is(typeMapper));
assertThat(mmc).isNotNull();
assertThat(mmc.getTypeMapper()).isEqualTo(typeMapper);
context.close();
}
@@ -137,8 +137,8 @@ public class AbstractReactiveMongoConfigurationUnitTests {
ConfigurationWithMultipleBasePackages config = new ConfigurationWithMultipleBasePackages();
Set<Class<?>> entities = config.getInitialEntitySet();
assertThat(entities, hasSize(2));
assertThat(entities, hasItems(First.class, Second.class));
assertThat(entities).hasSize(2);
assertThat(entities).contains(First.class, Second.class);
}
private static void assertScanningDisabled(final String value) throws ClassNotFoundException {
@@ -150,8 +150,8 @@ public class AbstractReactiveMongoConfigurationUnitTests {
}
};
assertThat(configuration.getMappingBasePackages(), hasItem(value));
assertThat(configuration.getInitialEntitySet(), hasSize(0));
assertThat(configuration.getMappingBasePackages()).contains(value);
assertThat(configuration.getInitialEntitySet()).hasSize(0);
}
@Configuration

View File

@@ -15,11 +15,11 @@
*/
package org.springframework.data.mongodb.config;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.joda.time.DateTime;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.annotation.CreatedDate;
@@ -50,16 +50,16 @@ public class AuditingIntegrationTests {
Entity entity = new Entity();
entity = callbacks.callback(BeforeConvertCallback.class, entity, "collection-1");
assertThat(entity.created, is(notNullValue()));
assertThat(entity.modified, is(entity.created));
assertThat(entity.created).isNotNull();
assertThat(entity.modified).isEqualTo(entity.created);
Thread.sleep(10);
entity.id = 1L;
entity = callbacks.callback(BeforeConvertCallback.class, entity, "collection-1");
assertThat(entity.created, is(notNullValue()));
assertThat(entity.modified, is(not(entity.created)));
assertThat(entity.created).isNotNull();
assertThat(entity.modified).isNotEqualTo(entity.created);
context.close();
}

View File

@@ -15,9 +15,7 @@
*/
package org.springframework.data.mongodb.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.Collections;
@@ -27,6 +25,7 @@ import java.util.function.Function;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
@@ -100,9 +99,9 @@ public class AuditingViaJavaConfigRepositoriesTests {
AuditablePerson createdBy = savedUser.getCreatedBy();
assertThat(createdBy, is(notNullValue()));
assertThat(createdBy.getFirstname(), is(this.auditor.getFirstname()));
assertThat(savedUser.getCreatedAt(), is(notNullValue()));
assertThat(createdBy).isNotNull();
assertThat(createdBy.getFirstname()).isEqualTo(this.auditor.getFirstname());
assertThat(savedUser.getCreatedAt()).isNotNull();
}
@Test // DATAMONGO-843

View File

@@ -15,11 +15,11 @@
*/
package org.springframework.data.mongodb.config;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.geo.GeoJsonModule;
@@ -44,6 +44,6 @@ public class GeoJsonConfigurationIntegrationTests {
@Test // DATAMONGO-1181
public void picksUpGeoJsonModuleConfigurationByDefault() {
assertThat(geoJsonModule, is(notNullValue()));
assertThat(geoJsonModule).isNotNull();
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.config;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Collections;
import java.util.Set;
@@ -25,6 +24,7 @@ import org.bson.Document;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanReference;
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
@@ -72,7 +72,7 @@ public class MappingMongoConverterParserIntegrationTests {
MappingMongoConverter converter = factory.getBean("converter", MappingMongoConverter.class);
MongoTypeMapper customMongoTypeMapper = factory.getBean(CustomMongoTypeMapper.class);
assertThat(converter.getTypeMapper(), is(customMongoTypeMapper));
assertThat(converter.getTypeMapper()).isEqualTo(customMongoTypeMapper);
}
@Test // DATAMONGO-301
@@ -80,8 +80,8 @@ public class MappingMongoConverterParserIntegrationTests {
loadValidConfiguration();
CustomConversions conversions = factory.getBean(CustomConversions.class);
assertThat(conversions.hasCustomWriteTarget(Person.class), is(true));
assertThat(conversions.hasCustomWriteTarget(Account.class), is(true));
assertThat(conversions.hasCustomWriteTarget(Person.class)).isTrue();
assertThat(conversions.hasCustomWriteTarget(Account.class)).isTrue();
}
@Test // DATAMONGO-607
@@ -91,9 +91,9 @@ public class MappingMongoConverterParserIntegrationTests {
BeanDefinition definition = factory.getBeanDefinition("abbreviatingConverter.mongoMappingContext");
Object value = definition.getPropertyValues().getPropertyValue("fieldNamingStrategy").getValue();
assertThat(value, is(instanceOf(BeanDefinition.class)));
assertThat(value).isInstanceOf(BeanDefinition.class);
BeanDefinition strategy = (BeanDefinition) value;
assertThat(strategy.getBeanClassName(), is(CamelCaseAbbreviatingFieldNamingStrategy.class.getName()));
assertThat(strategy.getBeanClassName()).isEqualTo(CamelCaseAbbreviatingFieldNamingStrategy.class.getName());
}
@Test // DATAMONGO-866
@@ -151,7 +151,7 @@ public class MappingMongoConverterParserIntegrationTests {
BeanReference value = (BeanReference) definition.getPropertyValues().getPropertyValue("fieldNamingStrategy")
.getValue();
assertThat(value.getBeanName(), is("customFieldNamingStrategy"));
assertThat(value.getBeanName()).isEqualTo("customFieldNamingStrategy");
}
@Component

View File

@@ -15,11 +15,11 @@
*/
package org.springframework.data.mongodb.config;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
@@ -50,14 +50,14 @@ public class MappingMongoConverterParserValidationIntegrationTests {
public void validatingEventListenerCreatedWithDefaultConfig() {
reader.loadBeanDefinitions(new ClassPathResource("namespace/converter-default.xml"));
assertThat(factory.getBean(BeanNames.VALIDATING_EVENT_LISTENER_BEAN_NAME), is(not(nullValue())));
assertThat(factory.getBean(BeanNames.VALIDATING_EVENT_LISTENER_BEAN_NAME)).isNotNull();
}
@Test // DATAMONGO-36
public void validatingEventListenerCreatedWhenValidationEnabled() {
reader.loadBeanDefinitions(new ClassPathResource("namespace/converter-validation-enabled.xml"));
assertThat(factory.getBean(BeanNames.VALIDATING_EVENT_LISTENER_BEAN_NAME), is(not(nullValue())));
assertThat(factory.getBean(BeanNames.VALIDATING_EVENT_LISTENER_BEAN_NAME)).isNotNull();
}
@Test(expected = NoSuchBeanDefinitionException.class) // DATAMONGO-36
@@ -71,6 +71,6 @@ public class MappingMongoConverterParserValidationIntegrationTests {
public void validatingEventListenerCreatedWithCustomTypeMapperConfig() {
reader.loadBeanDefinitions(new ClassPathResource("namespace/converter-custom-typeMapper.xml"));
assertThat(factory.getBean(BeanNames.VALIDATING_EVENT_LISTENER_BEAN_NAME), is(not(nullValue())));
assertThat(factory.getBean(BeanNames.VALIDATING_EVENT_LISTENER_BEAN_NAME)).isNotNull();
}
}

View File

@@ -15,11 +15,11 @@
*/
package org.springframework.data.mongodb.config;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.data.mongodb.MongoDbFactory;
@@ -41,7 +41,7 @@ public class MongoDbFactoryNoDatabaseRunningTests {
@Test // DATAMONGO-139
public void startsUpWithoutADatabaseRunning() {
assertThat(mongoTemplate.getClass().getName(), is("org.springframework.data.mongodb.core.MongoTemplate"));
assertThat(mongoTemplate.getClass().getName()).isEqualTo("org.springframework.data.mongodb.core.MongoTemplate");
}
@Test(expected = DataAccessResourceFailureException.class)

View File

@@ -16,18 +16,17 @@
package org.springframework.data.mongodb.config;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import com.mongodb.MongoClient;
import org.bson.Document;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.mongodb.core.MongoClientFactoryBean;
@@ -36,7 +35,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.util.ReflectionTestUtils;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
/**
@@ -56,34 +55,34 @@ public class MongoNamespaceReplicaSetTests {
@SuppressWarnings("unchecked")
public void testParsingMongoWithReplicaSets() throws Exception {
assertTrue(ctx.containsBean("replicaSetMongo"));
assertThat(ctx.containsBean("replicaSetMongo")).isTrue();
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&replicaSetMongo");
List<ServerAddress> replicaSetSeeds = (List<ServerAddress>) ReflectionTestUtils.getField(mfb, "replicaSetSeeds");
assertThat(replicaSetSeeds, is(notNullValue()));
assertThat(replicaSetSeeds, hasItems(new ServerAddress(InetAddress.getByName("127.0.0.1"), 10001),
new ServerAddress(InetAddress.getByName("localhost"), 10002)));
assertThat(replicaSetSeeds).isNotNull();
assertThat(replicaSetSeeds).contains(new ServerAddress(InetAddress.getByName("127.0.0.1"), 10001),
new ServerAddress(InetAddress.getByName("localhost"), 10002));
}
@Test
@SuppressWarnings("unchecked")
public void testParsingWithPropertyPlaceHolder() throws Exception {
assertTrue(ctx.containsBean("manyReplicaSetMongo"));
assertThat(ctx.containsBean("manyReplicaSetMongo")).isTrue();
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&manyReplicaSetMongo");
List<ServerAddress> replicaSetSeeds = (List<ServerAddress>) ReflectionTestUtils.getField(mfb, "replicaSetSeeds");
assertThat(replicaSetSeeds, is(notNullValue()));
assertThat(replicaSetSeeds, hasSize(3));
assertThat(replicaSetSeeds).isNotNull();
assertThat(replicaSetSeeds).hasSize(3);
List<Integer> ports = new ArrayList<Integer>();
for (ServerAddress replicaSetSeed : replicaSetSeeds) {
ports.add(replicaSetSeed.getPort());
}
assertThat(ports, hasItems(27017, 27018, 27019));
assertThat(ports).contains(27017, 27018, 27019);
}
@Test
@@ -91,15 +90,15 @@ public class MongoNamespaceReplicaSetTests {
public void testMongoWithReplicaSets() {
MongoClient mongo = ctx.getBean(MongoClient.class);
assertEquals(2, mongo.getAllAddress().size());
assertThat(mongo.getAllAddress().size()).isEqualTo(2);
List<ServerAddress> servers = mongo.getAllAddress();
assertEquals("127.0.0.1", servers.get(0).getHost());
assertEquals("localhost", servers.get(1).getHost());
assertEquals(10001, servers.get(0).getPort());
assertEquals(10002, servers.get(1).getPort());
assertThat(servers.get(0).getHost()).isEqualTo("127.0.0.1");
assertThat(servers.get(1).getHost()).isEqualTo("localhost");
assertThat(servers.get(0).getPort()).isEqualTo(10001);
assertThat(servers.get(1).getPort()).isEqualTo(10002);
MongoTemplate template = new MongoTemplate(mongo, "admin");
Document result = template.executeCommand("{replSetGetStatus : 1}");
assertEquals("blort", result.get("set").toString());
assertThat(result.get("set").toString()).isEqualTo("blort");
}
}

View File

@@ -15,13 +15,14 @@
*/
package org.springframework.data.mongodb.config;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.test.util.ReflectionTestUtils.*;
import javax.net.ssl.SSLSocketFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.mongodb.MongoDbFactory;
@@ -54,177 +55,180 @@ public class MongoNamespaceTests {
@Test
public void testMongoSingleton() throws Exception {
assertTrue(ctx.containsBean("noAttrMongo"));
assertThat(ctx.containsBean("noAttrMongo")).isTrue();
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&noAttrMongo");
assertNull(getField(mfb, "host"));
assertNull(getField(mfb, "port"));
assertThat(getField(mfb, "host")).isNull();
assertThat(getField(mfb, "port")).isNull();
}
@Test
public void testMongoSingletonWithAttributes() throws Exception {
assertTrue(ctx.containsBean("defaultMongo"));
assertThat(ctx.containsBean("defaultMongo")).isTrue();
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&defaultMongo");
String host = (String) getField(mfb, "host");
Integer port = (Integer) getField(mfb, "port");
assertEquals("localhost", host);
assertEquals(new Integer(27017), port);
assertThat(host).isEqualTo("localhost");
assertThat(port).isEqualTo(new Integer(27017));
MongoClientOptions options = (MongoClientOptions) getField(mfb, "mongoClientOptions");
assertFalse("By default socketFactory should not be a SSLSocketFactory",
options.getSocketFactory() instanceof SSLSocketFactory);
assertThat(options.getSocketFactory() instanceof SSLSocketFactory)
.as("By default socketFactory should not be a SSLSocketFactory").isFalse();
}
@Test // DATAMONGO-764
public void testMongoSingletonWithSslEnabled() throws Exception {
assertTrue(ctx.containsBean("mongoSsl"));
assertThat(ctx.containsBean("mongoSsl")).isTrue();
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoSsl");
MongoClientOptions options = (MongoClientOptions) getField(mfb, "mongoClientOptions");
assertTrue("socketFactory should be a SSLSocketFactory", options.getSocketFactory() instanceof SSLSocketFactory);
assertThat(options.getSocketFactory() instanceof SSLSocketFactory).as("socketFactory should be a SSLSocketFactory")
.isTrue();
}
@Test // DATAMONGO-1490
public void testMongoClientSingletonWithSslEnabled() {
assertTrue(ctx.containsBean("mongoClientSsl"));
assertThat(ctx.containsBean("mongoClientSsl")).isTrue();
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoClientSsl");
MongoClientOptions options = (MongoClientOptions) getField(mfb, "mongoClientOptions");
assertTrue("socketFactory should be a SSLSocketFactory", options.getSocketFactory() instanceof SSLSocketFactory);
assertThat(options.getSocketFactory() instanceof SSLSocketFactory).as("socketFactory should be a SSLSocketFactory")
.isTrue();
}
@Test // DATAMONGO-764
public void testMongoSingletonWithSslEnabledAndCustomSslSocketFactory() throws Exception {
assertTrue(ctx.containsBean("mongoSslWithCustomSslFactory"));
assertThat(ctx.containsBean("mongoSslWithCustomSslFactory")).isTrue();
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoSslWithCustomSslFactory");
SSLSocketFactory customSslSocketFactory = ctx.getBean("customSslSocketFactory", SSLSocketFactory.class);
MongoClientOptions options = (MongoClientOptions) getField(mfb, "mongoClientOptions");
assertTrue("socketFactory should be a SSLSocketFactory", options.getSocketFactory() instanceof SSLSocketFactory);
assertSame(customSslSocketFactory, options.getSocketFactory());
assertThat(options.getSocketFactory() instanceof SSLSocketFactory).as("socketFactory should be a SSLSocketFactory")
.isTrue();
assertThat(options.getSocketFactory()).isSameAs(customSslSocketFactory);
}
@Test
public void testSecondMongoDbFactory() {
assertTrue(ctx.containsBean("secondMongoDbFactory"));
assertThat(ctx.containsBean("secondMongoDbFactory")).isTrue();
MongoDbFactory dbf = (MongoDbFactory) ctx.getBean("secondMongoDbFactory");
MongoClient mongo = (MongoClient) getField(dbf, "mongoClient");
assertEquals("127.0.0.1", mongo.getAddress().getHost());
assertEquals(27017, mongo.getAddress().getPort());
assertEquals("database", getField(dbf, "databaseName"));
assertThat(mongo.getAddress().getHost()).isEqualTo("127.0.0.1");
assertThat(mongo.getAddress().getPort()).isEqualTo(27017);
assertThat(getField(dbf, "databaseName")).isEqualTo("database");
}
@Test // DATAMONGO-789
public void testThirdMongoDbFactory() {
assertTrue(ctx.containsBean("thirdMongoDbFactory"));
assertThat(ctx.containsBean("thirdMongoDbFactory")).isTrue();
MongoDbFactory dbf = (MongoDbFactory) ctx.getBean("thirdMongoDbFactory");
MongoClient mongo = (MongoClient) getField(dbf, "mongoClient");
assertEquals("127.0.0.1", mongo.getAddress().getHost());
assertEquals(27017, mongo.getAddress().getPort());
assertEquals("database", getField(dbf, "databaseName"));
assertThat(mongo.getAddress().getHost()).isEqualTo("127.0.0.1");
assertThat(mongo.getAddress().getPort()).isEqualTo(27017);
assertThat(getField(dbf, "databaseName")).isEqualTo("database");
}
@Test // DATAMONGO-140
public void testMongoTemplateFactory() {
assertTrue(ctx.containsBean("mongoTemplate"));
assertThat(ctx.containsBean("mongoTemplate")).isTrue();
MongoOperations operations = (MongoOperations) ctx.getBean("mongoTemplate");
MongoDbFactory dbf = (MongoDbFactory) getField(operations, "mongoDbFactory");
assertEquals("database", getField(dbf, "databaseName"));
assertThat(getField(dbf, "databaseName")).isEqualTo("database");
MongoConverter converter = (MongoConverter) getField(operations, "mongoConverter");
assertNotNull(converter);
assertThat(converter).isNotNull();
}
@Test // DATAMONGO-140
public void testSecondMongoTemplateFactory() {
assertTrue(ctx.containsBean("anotherMongoTemplate"));
assertThat(ctx.containsBean("anotherMongoTemplate")).isTrue();
MongoOperations operations = (MongoOperations) ctx.getBean("anotherMongoTemplate");
MongoDbFactory dbf = (MongoDbFactory) getField(operations, "mongoDbFactory");
assertEquals("database", getField(dbf, "databaseName"));
assertThat(getField(dbf, "databaseName")).isEqualTo("database");
WriteConcern writeConcern = (WriteConcern) getField(operations, "writeConcern");
assertEquals(WriteConcern.SAFE, writeConcern);
assertThat(writeConcern).isEqualTo(WriteConcern.SAFE);
}
@Test // DATAMONGO-628
public void testGridFsTemplateFactory() {
assertTrue(ctx.containsBean("gridFsTemplate"));
assertThat(ctx.containsBean("gridFsTemplate")).isTrue();
GridFsOperations operations = (GridFsOperations) ctx.getBean("gridFsTemplate");
MongoDbFactory dbf = (MongoDbFactory) getField(operations, "dbFactory");
assertEquals("database", getField(dbf, "databaseName"));
assertThat(getField(dbf, "databaseName")).isEqualTo("database");
MongoConverter converter = (MongoConverter) getField(operations, "converter");
assertNotNull(converter);
assertThat(converter).isNotNull();
}
@Test // DATAMONGO-628
public void testSecondGridFsTemplateFactory() {
assertTrue(ctx.containsBean("secondGridFsTemplate"));
assertThat(ctx.containsBean("secondGridFsTemplate")).isTrue();
GridFsOperations operations = (GridFsOperations) ctx.getBean("secondGridFsTemplate");
MongoDbFactory dbf = (MongoDbFactory) getField(operations, "dbFactory");
assertEquals("database", getField(dbf, "databaseName"));
assertEquals(null, getField(operations, "bucket"));
assertThat(getField(dbf, "databaseName")).isEqualTo("database");
assertThat(getField(operations, "bucket")).isEqualTo(null);
MongoConverter converter = (MongoConverter) getField(operations, "converter");
assertNotNull(converter);
assertThat(converter).isNotNull();
}
@Test // DATAMONGO-823
public void testThirdGridFsTemplateFactory() {
assertTrue(ctx.containsBean("thirdGridFsTemplate"));
assertThat(ctx.containsBean("thirdGridFsTemplate")).isTrue();
GridFsOperations operations = (GridFsOperations) ctx.getBean("thirdGridFsTemplate");
MongoDbFactory dbf = (MongoDbFactory) getField(operations, "dbFactory");
assertEquals("database", getField(dbf, "databaseName"));
assertEquals("bucketString", getField(operations, "bucket"));
assertThat(getField(dbf, "databaseName")).isEqualTo("database");
assertThat(getField(operations, "bucket")).isEqualTo("bucketString");
MongoConverter converter = (MongoConverter) getField(operations, "converter");
assertNotNull(converter);
assertThat(converter).isNotNull();
}
@Test
@SuppressWarnings("deprecation")
public void testMongoSingletonWithPropertyPlaceHolders() throws Exception {
assertTrue(ctx.containsBean("mongoClient"));
assertThat(ctx.containsBean("mongoClient")).isTrue();
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoClient");
String host = (String) getField(mfb, "host");
Integer port = (Integer) getField(mfb, "port");
assertEquals("127.0.0.1", host);
assertEquals(new Integer(27017), port);
assertThat(host).isEqualTo("127.0.0.1");
assertThat(port).isEqualTo(new Integer(27017));
MongoClient mongo = mfb.getObject();
MongoClientOptions mongoOpts = mongo.getMongoClientOptions();
assertEquals(8, mongoOpts.getConnectionsPerHost());
assertEquals(1000, mongoOpts.getConnectTimeout());
assertEquals(1500, mongoOpts.getMaxWaitTime());
assertThat(mongoOpts.getConnectionsPerHost()).isEqualTo(8);
assertThat(mongoOpts.getConnectTimeout()).isEqualTo(1000);
assertThat(mongoOpts.getMaxWaitTime()).isEqualTo(1500);
assertEquals(1500, mongoOpts.getSocketTimeout());
assertEquals(4, mongoOpts.getThreadsAllowedToBlockForConnectionMultiplier());
assertThat(mongoOpts.getSocketTimeout()).isEqualTo(1500);
assertThat(mongoOpts.getThreadsAllowedToBlockForConnectionMultiplier()).isEqualTo(4);
// TODO: check the damned defaults
// assertEquals("w", mongoOpts.getWriteConcern().getW());

View File

@@ -15,13 +15,13 @@
*/
package org.springframework.data.mongodb.config;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionReader;
@@ -58,10 +58,10 @@ public class MongoParserIntegrationTests {
List<PropertyValue> values = definition.getPropertyValues().getPropertyValueList();
assertThat(values.get(2).getValue(), instanceOf(BeanDefinition.class));
assertThat(values.get(2).getValue()).isInstanceOf(BeanDefinition.class);
BeanDefinition x = (BeanDefinition) values.get(2).getValue();
assertThat(x.getPropertyValues().getPropertyValueList(), hasItem(new PropertyValue("writeConcern", "SAFE")));
assertThat(x.getPropertyValues().getPropertyValueList()).contains(new PropertyValue("writeConcern", "SAFE"));
factory.getBean("mongoClient");
}
@@ -74,7 +74,7 @@ public class MongoParserIntegrationTests {
AbstractApplicationContext context = new GenericApplicationContext(factory);
context.refresh();
assertThat(context.getBean("mongo2", Mongo.class), is(notNullValue()));
assertThat(context.getBean("mongo2", Mongo.class)).isNotNull();
context.close();
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.config;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Before;
import org.junit.Rule;
@@ -56,7 +55,7 @@ public class ReadPreferencePropertyEditorUnitTests {
editor.setAsText("secondary");
assertThat(editor.getValue(), is((Object) ReadPreference.secondary()));
assertThat(editor.getValue()).isEqualTo((Object) ReadPreference.secondary());
}
@Test // DATAMONGO-1158
@@ -64,6 +63,6 @@ public class ReadPreferencePropertyEditorUnitTests {
editor.setAsText("NEAREST");
assertThat(editor.getValue(), is((Object) ReadPreference.nearest()));
assertThat(editor.getValue()).isEqualTo((Object) ReadPreference.nearest());
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.config;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.io.IOException;
import java.net.InetAddress;
@@ -24,7 +23,6 @@ import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -78,7 +76,7 @@ public class ServerAddressPropertyEditorUnitTests {
public void interpretEmptyStringAsNull() {
editor.setAsText("");
assertNull(editor.getValue());
assertThat(editor.getValue()).isNull();
}
@Test // DATAMONGO-808
@@ -161,13 +159,13 @@ public class ServerAddressPropertyEditorUnitTests {
private static void assertSingleAddressWithPort(String hostAddress, Integer port, Object result)
throws UnknownHostException {
assertThat(result, is(instanceOf(ServerAddress[].class)));
assertThat(result).isInstanceOf(ServerAddress[].class);
Collection<ServerAddress> addresses = Arrays.asList((ServerAddress[]) result);
assertThat(addresses, hasSize(1));
assertThat(addresses).hasSize(1);
if (port == null) {
assertThat(addresses, hasItem(new ServerAddress(InetAddress.getByName(hostAddress))));
assertThat(addresses).contains(new ServerAddress(InetAddress.getByName(hostAddress)));
} else {
assertThat(addresses, hasItem(new ServerAddress(InetAddress.getByName(hostAddress), port)));
assertThat(addresses).contains(new ServerAddress(InetAddress.getByName(hostAddress), port));
}
}
@@ -176,7 +174,7 @@ public class ServerAddressPropertyEditorUnitTests {
for (String hostname : hostnames) {
try {
InetAddress.getByName(hostname).isReachable(1500);
Assert.fail("Supposedly unresolveable hostname '" + hostname + "' can be resolved.");
fail("Supposedly unresolveable hostname '" + hostname + "' can be resolved.");
} catch (IOException expected) {
// ok
}

View File

@@ -15,9 +15,7 @@
*/
package org.springframework.data.mongodb.core;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.junit.Assume.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.core.query.Query.*;
@@ -26,6 +24,7 @@ import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -88,18 +87,18 @@ public class DefaultScriptOperationsTests {
@Test // DATAMONGO-479
public void executeShouldDirectlyRunExecutableMongoScript() {
assertThat(scriptOps.execute(EXECUTABLE_SCRIPT, 10), is((Object) 10D));
assertThat(scriptOps.execute(EXECUTABLE_SCRIPT, 10)).isEqualTo((Object) 10D);
}
@Test // DATAMONGO-479
public void saveShouldStoreCallableScriptCorrectly() {
Query query = query(where("_id").is(SCRIPT_NAME));
assumeThat(template.exists(query, JAVASCRIPT_COLLECTION_NAME), is(false));
assertThat(template.exists(query, JAVASCRIPT_COLLECTION_NAME)).isFalse();
scriptOps.register(CALLABLE_SCRIPT);
assumeThat(template.exists(query, JAVASCRIPT_COLLECTION_NAME), is(true));
assertThat(template.exists(query, JAVASCRIPT_COLLECTION_NAME)).isTrue();
}
@Test // DATAMONGO-479
@@ -108,7 +107,7 @@ public class DefaultScriptOperationsTests {
NamedMongoScript script = scriptOps.register(EXECUTABLE_SCRIPT);
Query query = query(where("_id").is(script.getName()));
assumeThat(template.exists(query, JAVASCRIPT_COLLECTION_NAME), is(true));
assertThat(template.exists(query, JAVASCRIPT_COLLECTION_NAME)).isTrue();
}
@Test // DATAMONGO-479
@@ -117,11 +116,11 @@ public class DefaultScriptOperationsTests {
scriptOps.register(CALLABLE_SCRIPT);
Query query = query(where("_id").is(SCRIPT_NAME));
assumeThat(template.exists(query, JAVASCRIPT_COLLECTION_NAME), is(true));
assertThat(template.exists(query, JAVASCRIPT_COLLECTION_NAME)).isTrue();
Object result = scriptOps.call(CALLABLE_SCRIPT.getName(), 10);
assertThat(result, is((Object) 10D));
assertThat(result).isEqualTo(10D);
}
@Test // DATAMONGO-479
@@ -129,12 +128,12 @@ public class DefaultScriptOperationsTests {
scriptOps.register(CALLABLE_SCRIPT);
assertThat(scriptOps.exists(SCRIPT_NAME), is(true));
assertThat(scriptOps.exists(SCRIPT_NAME)).isTrue();
}
@Test // DATAMONGO-479
public void existsShouldReturnFalseIfScriptNotAvailableOnServer() {
assertThat(scriptOps.exists(SCRIPT_NAME), is(false));
assertThat(scriptOps.exists(SCRIPT_NAME)).isFalse();
}
@Test // DATAMONGO-479
@@ -144,7 +143,7 @@ public class DefaultScriptOperationsTests {
Object result = scriptOps.call(SCRIPT_NAME, 10);
assertThat(result, is((Object) 10D));
assertThat(result).isEqualTo((Object) 10D);
}
@Test(expected = UncategorizedDataAccessException.class) // DATAMONGO-479
@@ -157,16 +156,16 @@ public class DefaultScriptOperationsTests {
scriptOps.register(CALLABLE_SCRIPT);
assertThat(scriptOps.getScriptNames(), hasItems("echo"));
assertThat(scriptOps.getScriptNames()).contains("echo");
}
@Test // DATAMONGO-479
public void scriptNamesShouldReturnEmptySetWhenNoScriptRegistered() {
assertThat(scriptOps.getScriptNames(), is(empty()));
assertThat(scriptOps.getScriptNames()).isEmpty();
}
@Test // DATAMONGO-1465
public void executeShouldNotQuoteStrings() {
assertThat(scriptOps.execute(EXECUTABLE_SCRIPT, "spring-data"), is((Object) "spring-data"));
assertThat(scriptOps.execute(EXECUTABLE_SCRIPT, "spring-data")).isEqualTo((Object) "spring-data");
}
}

View File

@@ -15,16 +15,16 @@
*/
package org.springframework.data.mongodb.core;
import static org.hamcrest.core.IsNull.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.mongodb.core.script.ExecutableMongoScript;
import org.springframework.data.mongodb.core.script.NamedMongoScript;
@@ -72,7 +72,7 @@ public class DefaultScriptOperationsUnitTests {
ArgumentCaptor<NamedMongoScript> captor = ArgumentCaptor.forClass(NamedMongoScript.class);
verify(mongoOperations, times(1)).save(captor.capture(), eq("system.js"));
Assert.assertThat(captor.getValue().getName(), notNullValue());
assertThat(captor.getValue().getName()).isNotNull();
}
@Test(expected = IllegalArgumentException.class) // DATAMONGO-479

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.bson.Document;
import org.junit.Test;
@@ -38,10 +37,10 @@ public class GeoCommandStatisticsUnitTests {
public void fallsBackToNanIfNoAverageDistanceIsAvailable() {
GeoCommandStatistics statistics = GeoCommandStatistics.from(new Document("stats", null));
assertThat(statistics.getAverageDistance(), is(Double.NaN));
assertThat(statistics.getAverageDistance()).isEqualTo(Double.NaN);
statistics = GeoCommandStatistics.from(new Document("stats", new Document()));
assertThat(statistics.getAverageDistance(), is(Double.NaN));
assertThat(statistics.getAverageDistance()).isEqualTo(Double.NaN);
}
@Test // DATAMONGO-1361
@@ -50,6 +49,6 @@ public class GeoCommandStatisticsUnitTests {
GeoCommandStatistics statistics = GeoCommandStatistics
.from(new Document("stats", new Document("avgDistance", 1.5)));
assertThat(statistics.getAverageDistance(), is(1.5));
assertThat(statistics.getAverageDistance()).isEqualTo(1.5);
}
}

View File

@@ -15,10 +15,10 @@
*/
package org.springframework.data.mongodb.core;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.data.mongodb.config.ReadPreferencePropertyEditor;
@@ -45,6 +45,6 @@ public class MongoClientOptionsFactoryBeanIntegrationTests {
factory.registerBeanDefinition("factory", definition);
MongoClientOptionsFactoryBean bean = factory.getBean("&factory", MongoClientOptionsFactoryBean.class);
assertThat(ReflectionTestUtils.getField(bean, "readPreference"), is((Object) ReadPreference.nearest()));
assertThat(ReflectionTestUtils.getField(bean, "readPreference")).isEqualTo((Object) ReadPreference.nearest());
}
}

View File

@@ -15,14 +15,14 @@
*/
package org.springframework.data.mongodb.core;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.net.UnknownHostException;
import org.bson.BsonDocument;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.NestedRuntimeException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
@@ -127,7 +127,7 @@ public class MongoExceptionTranslatorUnitTests {
public void translateUnsupportedException() {
RuntimeException exception = new RuntimeException();
assertThat(translator.translateExceptionIfPossible(exception), is(nullValue()));
assertThat(translator.translateExceptionIfPossible(exception)).isNull();
}
@Test // DATAMONGO-2045
@@ -156,11 +156,11 @@ public class MongoExceptionTranslatorUnitTests {
DataAccessException translated = translator.translateExceptionIfPossible(new MongoException(code, ""));
assertThat("Expected exception of type " + clazz.getName() + "!", translated, is(not(nullValue())));
assertThat(translated).as("Expected exception of type " + clazz.getName() + "!").isNotNull();
Throwable cause = translated.getRootCause();
assertThat(cause, is(instanceOf(MongoException.class)));
assertThat(((MongoException) cause).getCode(), is(code));
assertThat(cause).isInstanceOf(MongoException.class);
assertThat(((MongoException) cause).getCode()).isEqualTo(code);
}
private static void expectExceptionWithCauseMessage(NestedRuntimeException e,
@@ -171,11 +171,11 @@ public class MongoExceptionTranslatorUnitTests {
private static void expectExceptionWithCauseMessage(NestedRuntimeException e,
Class<? extends NestedRuntimeException> type, String message) {
assertThat(e, is(instanceOf(type)));
assertThat(e).isInstanceOf(type);
if (message != null) {
assertThat(e.getRootCause(), is(notNullValue()));
assertThat(e.getRootCause().getMessage(), containsString(message));
assertThat(e.getRootCause()).isNotNull();
assertThat(e.getRootCause().getMessage()).contains(message);
}
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core;
import static org.hamcrest.core.Is.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.core.query.Query.*;
@@ -26,6 +25,7 @@ import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
@@ -80,7 +80,7 @@ public class NoExplicitIdTests {
TypeWithoutIdProperty retrieved = mongoOps.findOne(query(where("someString").is(noid.someString)),
TypeWithoutIdProperty.class);
assertThat(retrieved.someString, is(noid.someString));
assertThat(retrieved.someString).isEqualTo(noid.someString);
}
@Test // DATAMONGO-1289
@@ -92,7 +92,7 @@ public class NoExplicitIdTests {
repo.save(noid);
TypeWithoutIdProperty retrieved = repo.findBySomeString(noid.someString);
assertThat(retrieved.someString, is(noid.someString));
assertThat(retrieved.someString).isEqualTo(noid.someString);
}
@Test // DATAMONGO-1289
@@ -108,7 +108,7 @@ public class NoExplicitIdTests {
"typeWithoutIdProperty");
Optional<TypeWithoutIdProperty> retrieved = repo.findById(map.get("_id").toString());
assertThat(retrieved.get().someString, is(noid.someString));
assertThat(retrieved.get().someString).isEqualTo(noid.someString);
}
static class TypeWithoutIdProperty {

View File

@@ -15,8 +15,8 @@
*/
package org.springframework.data.mongodb.core;
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 static org.junit.Assume.*;
import reactor.core.publisher.Flux;
@@ -28,6 +28,7 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.mongodb.UncategorizedMongoDbException;
@@ -81,7 +82,7 @@ public class ReactiveMongoTemplateExecuteTests {
StepVerifier.create(operations.executeCommand("{ buildInfo: 1 }")).consumeNextWith(actual -> {
assertThat(actual, hasKey("version"));
assertThat(actual).containsKey("version");
}).verifyComplete();
}
@@ -90,7 +91,7 @@ public class ReactiveMongoTemplateExecuteTests {
StepVerifier.create(operations.executeCommand(new Document("buildInfo", 1))).consumeNextWith(actual -> {
assertThat(actual, hasKey("version"));
assertThat(actual).containsKey("version");
}).verifyComplete();
}
@@ -105,8 +106,8 @@ public class ReactiveMongoTemplateExecuteTests {
StepVerifier.create(operations.executeCommand("{ find: 'execute_test'}")) //
.consumeNextWith(actual -> {
assertThat(actual.get("ok", Double.class), is(closeTo(1D, 0D)));
assertThat(actual, hasKey("cursor"));
assertThat(actual.get("ok", Double.class)).isCloseTo(1D, offset(0D));
assertThat(actual).containsKey("cursor");
}) //
.verifyComplete();
}

View File

@@ -15,10 +15,8 @@
*/
package org.springframework.data.mongodb.core;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.any;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
import lombok.Data;
@@ -42,6 +40,7 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.StaticApplicationContext;
@@ -167,7 +166,7 @@ public class ReactiveMongoTemplateUnitTests {
@Test // DATAMONGO-1444
public void defaultsConverterToMappingMongoConverter() throws Exception {
ReactiveMongoTemplate template = new ReactiveMongoTemplate(mongoClient, "database");
assertTrue(ReflectionTestUtils.getField(template, "mongoConverter") instanceof MappingMongoConverter);
assertThat(ReflectionTestUtils.getField(template, "mongoConverter") instanceof MappingMongoConverter).isTrue();
}
@Test // DATAMONGO-1912
@@ -180,7 +179,7 @@ public class ReactiveMongoTemplateUnitTests {
Map<String, String> entity = new LinkedHashMap<>();
StepVerifier.create(template.save(entity, "foo")).consumeNextWith(actual -> {
assertThat(entity, hasKey("_id"));
assertThat(entity).containsKey("_id");
}).verifyComplete();
}
@@ -231,7 +230,7 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<FindOneAndUpdateOptions> options = ArgumentCaptor.forClass(FindOneAndUpdateOptions.class);
verify(collection).findOneAndUpdate(any(), any(), options.capture());
assertThat(options.getValue().getCollation().getLocale(), is("fr"));
assertThat(options.getValue().getCollation().getLocale()).isEqualTo("fr");
}
@Test // DATAMONGO-1518
@@ -244,7 +243,7 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<FindOneAndDeleteOptions> options = ArgumentCaptor.forClass(FindOneAndDeleteOptions.class);
verify(collection).findOneAndDelete(any(), options.capture());
assertThat(options.getValue().getCollation().getLocale(), is("fr"));
assertThat(options.getValue().getCollation().getLocale()).isEqualTo("fr");
}
@Test // DATAMONGO-1518
@@ -258,7 +257,7 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<DeleteOptions> options = ArgumentCaptor.forClass(DeleteOptions.class);
verify(collection).deleteMany(any(), options.capture());
assertThat(options.getValue().getCollation().getLocale(), is("fr"));
assertThat(options.getValue().getCollation().getLocale()).isEqualTo("fr");
}
@Test // DATAMONGO-1518
@@ -272,7 +271,7 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<UpdateOptions> options = ArgumentCaptor.forClass(UpdateOptions.class);
verify(collection).updateOne(any(), any(), options.capture());
assertThat(options.getValue().getCollation().getLocale(), is("fr"));
assertThat(options.getValue().getCollation().getLocale()).isEqualTo("fr");
}
@Test // DATAMONGO-1518
@@ -286,7 +285,7 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<UpdateOptions> options = ArgumentCaptor.forClass(UpdateOptions.class);
verify(collection).updateMany(any(), any(), options.capture());
assertThat(options.getValue().getCollation().getLocale(), is("fr"));
assertThat(options.getValue().getCollation().getLocale()).isEqualTo("fr");
}
@@ -301,7 +300,7 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<ReplaceOptions> options = ArgumentCaptor.forClass(ReplaceOptions.class);
verify(collection).replaceOne(any(Bson.class), any(), options.capture());
assertThat(options.getValue().getCollation().getLocale(), is("fr"));
assertThat(options.getValue().getCollation().getLocale()).isEqualTo("fr");
}
@Test // DATAMONGO-1518, DATAMONGO-2257
@@ -389,7 +388,7 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<CountOptions> options = ArgumentCaptor.forClass(CountOptions.class);
verify(collection).count(any(), options.capture());
assertThat(options.getValue().getSkip(), is(equalTo(10)));
assertThat(options.getValue().getSkip()).isEqualTo(10);
}
@Test // DATAMONGO-1783
@@ -400,7 +399,7 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<CountOptions> options = ArgumentCaptor.forClass(CountOptions.class);
verify(collection).count(any(), options.capture());
assertThat(options.getValue().getLimit(), is(equalTo(100)));
assertThat(options.getValue().getLimit()).isEqualTo(100);
}
@Test // DATAMONGO-2215
@@ -471,8 +470,8 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<FindOneAndUpdateOptions> options = ArgumentCaptor.forClass(FindOneAndUpdateOptions.class);
verify(collection).findOneAndUpdate(any(), any(), options.capture());
assertThat(options.getValue().getCollation(),
is(com.mongodb.client.model.Collation.builder().locale("de_AT").build()));
assertThat(options.getValue().getCollation())
.isEqualTo(com.mongodb.client.model.Collation.builder().locale("de_AT").build());
}
@Test // DATAMONGO-1854
@@ -483,8 +482,8 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<FindOneAndDeleteOptions> options = ArgumentCaptor.forClass(FindOneAndDeleteOptions.class);
verify(collection).findOneAndDelete(any(), options.capture());
assertThat(options.getValue().getCollation(),
is(com.mongodb.client.model.Collation.builder().locale("de_AT").build()));
assertThat(options.getValue().getCollation())
.isEqualTo(com.mongodb.client.model.Collation.builder().locale("de_AT").build());
}
@Test // DATAMONGO-1854
@@ -506,8 +505,8 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<CreateCollectionOptions> options = ArgumentCaptor.forClass(CreateCollectionOptions.class);
verify(db).createCollection(any(), options.capture());
assertThat(options.getValue().getCollation(),
is(com.mongodb.client.model.Collation.builder().locale("de_AT").build()));
assertThat(options.getValue().getCollation())
.isEqualTo(com.mongodb.client.model.Collation.builder().locale("de_AT").build());
}
@Test // DATAMONGO-1854
@@ -518,8 +517,8 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<CreateCollectionOptions> options = ArgumentCaptor.forClass(CreateCollectionOptions.class);
verify(db).createCollection(any(), options.capture());
assertThat(options.getValue().getCollation(),
is(com.mongodb.client.model.Collation.builder().locale("en_US").build()));
assertThat(options.getValue().getCollation())
.isEqualTo(com.mongodb.client.model.Collation.builder().locale("en_US").build());
}
@Test // DATAMONGO-1854
@@ -530,8 +529,8 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<CreateCollectionOptions> options = ArgumentCaptor.forClass(CreateCollectionOptions.class);
verify(db).createCollection(any(), options.capture());
assertThat(options.getValue().getCollation(),
is(com.mongodb.client.model.Collation.builder().locale("de_AT").build()));
assertThat(options.getValue().getCollation())
.isEqualTo(com.mongodb.client.model.Collation.builder().locale("de_AT").build());
}
@Test // DATAMONGO-1854
@@ -574,7 +573,7 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<FindOneAndReplaceOptions> options = ArgumentCaptor.forClass(FindOneAndReplaceOptions.class);
verify(collection).findOneAndReplace(any(Bson.class), any(), options.capture());
assertThat(options.getValue().getCollation().getLocale(), is("fr"));
assertThat(options.getValue().getCollation().getLocale()).isEqualTo("fr");
}
@Test // DATAMONGO-18545
@@ -585,7 +584,7 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<FindOneAndReplaceOptions> options = ArgumentCaptor.forClass(FindOneAndReplaceOptions.class);
verify(collection).findOneAndReplace(any(Bson.class), any(), options.capture());
assertThat(options.getValue().getCollation().getLocale(), is("de_AT"));
assertThat(options.getValue().getCollation().getLocale()).isEqualTo("de_AT");
}
@Test // DATAMONGO-18545
@@ -597,7 +596,7 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<FindOneAndReplaceOptions> options = ArgumentCaptor.forClass(FindOneAndReplaceOptions.class);
verify(collection).findOneAndReplace(any(Bson.class), any(), options.capture());
assertThat(options.getValue().getCollation().getLocale(), is("fr"));
assertThat(options.getValue().getCollation().getLocale()).isEqualTo("fr");
}
@Test // DATAMONGO-1854
@@ -625,8 +624,8 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<UpdateOptions> options = ArgumentCaptor.forClass(UpdateOptions.class);
verify(collection).updateOne(any(), any(), options.capture());
assertThat(options.getValue().getCollation(),
is(com.mongodb.client.model.Collation.builder().locale("de_AT").build()));
assertThat(options.getValue().getCollation())
.isEqualTo(com.mongodb.client.model.Collation.builder().locale("de_AT").build());
}
@Test // DATAMONGO-1854
@@ -638,8 +637,8 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<UpdateOptions> options = ArgumentCaptor.forClass(UpdateOptions.class);
verify(collection).updateOne(any(), any(), options.capture());
assertThat(options.getValue().getCollation(),
is(com.mongodb.client.model.Collation.builder().locale("fr").build()));
assertThat(options.getValue().getCollation())
.isEqualTo(com.mongodb.client.model.Collation.builder().locale("fr").build());
}
@Test // DATAMONGO-1854
@@ -650,8 +649,8 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<UpdateOptions> options = ArgumentCaptor.forClass(UpdateOptions.class);
verify(collection).updateMany(any(), any(), options.capture());
assertThat(options.getValue().getCollation(),
is(com.mongodb.client.model.Collation.builder().locale("de_AT").build()));
assertThat(options.getValue().getCollation())
.isEqualTo(com.mongodb.client.model.Collation.builder().locale("de_AT").build());
}
@Test // DATAMONGO-1854
@@ -663,8 +662,8 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<UpdateOptions> options = ArgumentCaptor.forClass(UpdateOptions.class);
verify(collection).updateMany(any(), any(), options.capture());
assertThat(options.getValue().getCollation(),
is(com.mongodb.client.model.Collation.builder().locale("fr").build()));
assertThat(options.getValue().getCollation())
.isEqualTo(com.mongodb.client.model.Collation.builder().locale("fr").build());
}
@Test // DATAMONGO-1854
@@ -675,8 +674,8 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<DeleteOptions> options = ArgumentCaptor.forClass(DeleteOptions.class);
verify(collection).deleteMany(any(), options.capture());
assertThat(options.getValue().getCollation(),
is(com.mongodb.client.model.Collation.builder().locale("de_AT").build()));
assertThat(options.getValue().getCollation())
.isEqualTo(com.mongodb.client.model.Collation.builder().locale("de_AT").build());
}
@Test // DATAMONGO-1854
@@ -687,8 +686,8 @@ public class ReactiveMongoTemplateUnitTests {
ArgumentCaptor<DeleteOptions> options = ArgumentCaptor.forClass(DeleteOptions.class);
verify(collection).deleteMany(any(), options.capture());
assertThat(options.getValue().getCollation(),
is(com.mongodb.client.model.Collation.builder().locale("fr").build()));
assertThat(options.getValue().getCollation())
.isEqualTo(com.mongodb.client.model.Collation.builder().locale("fr").build());
}
@Test // DATAMONGO-2261

View File

@@ -16,8 +16,6 @@
package org.springframework.data.mongodb.core;
import static org.assertj.core.api.Assertions.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
import static org.springframework.test.util.ReflectionTestUtils.*;
@@ -30,14 +28,15 @@ import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.test.util.ReflectionTestUtils;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.ClientSession;
import com.mongodb.client.MongoDatabase;
/**
* Unit tests for {@link SimpleMongoDbFactory}.
@@ -80,7 +79,7 @@ public class SimpleMongoDbFactoryUnitTests {
MongoClientURI mongoURI = new MongoClientURI("mongodb://myUsername:myPassword@localhost/myDatabase.myCollection");
MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoURI);
assertThat(getField(mongoDbFactory, "databaseName").toString(), is("myDatabase"));
assertThat(getField(mongoDbFactory, "databaseName").toString()).isEqualTo("myDatabase");
}
@Test // DATAMONGO-1158
@@ -89,7 +88,7 @@ public class SimpleMongoDbFactoryUnitTests {
MongoClientURI uri = new MongoClientURI("mongodb://myUserName:myPassWord@127.0.0.1:27017/myDataBase.myCollection");
SimpleMongoDbFactory factory = new SimpleMongoDbFactory(uri);
assertThat(getField(factory, "databaseName").toString(), is("myDataBase"));
assertThat(getField(factory, "databaseName").toString()).isEqualTo("myDataBase");
}
@Test // DATAMONGO-1880
@@ -105,7 +104,7 @@ public class SimpleMongoDbFactoryUnitTests {
Object singletonTarget = AopProxyUtils
.getSingletonTarget(ReflectionTestUtils.getField(invocationHandler, "advised"));
assertThat(singletonTarget, is(sameInstance(database)));
assertThat(singletonTarget).isSameAs(database);
}
private void rejectsDatabaseName(String databaseName) {

View File

@@ -16,8 +16,6 @@
package org.springframework.data.mongodb.core;
import static org.assertj.core.api.Assertions.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
import java.lang.reflect.InvocationHandler;
@@ -27,6 +25,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.data.mongodb.ReactiveMongoDatabaseFactory;
import org.springframework.test.util.ReflectionTestUtils;
@@ -60,7 +59,7 @@ public class SimpleReactiveMongoDatabaseFactoryUnitTests {
Object singletonTarget = AopProxyUtils
.getSingletonTarget(ReflectionTestUtils.getField(invocationHandler, "advised"));
assertThat(singletonTarget, is(sameInstance(database)));
assertThat(singletonTarget).isSameAs(database);
}
@Test // DATAMONGO-1903

View File

@@ -15,9 +15,8 @@
*/
package org.springframework.data.mongodb.core;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.bson.Document;
import org.junit.Before;
@@ -25,6 +24,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate.UnwrapAndReadDocumentCallback;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
@@ -62,8 +62,8 @@ public class UnwrapAndReadDocumentCallbackUnitTests {
Target target = callback.doWith(new Document("foo", "bar"));
assertThat(target.id, is(nullValue()));
assertThat(target.foo, is("bar"));
assertThat(target.id).isNull();
assertThat(target.foo).isEqualTo("bar");
}
@Test
@@ -71,8 +71,8 @@ public class UnwrapAndReadDocumentCallbackUnitTests {
Target target = callback.doWith(new Document("_id", new Document("foo", "bar")));
assertThat(target.id, is(nullValue()));
assertThat(target.foo, is("bar"));
assertThat(target.id).isNull();
assertThat(target.foo).isEqualTo("bar");
}
@Test
@@ -80,8 +80,8 @@ public class UnwrapAndReadDocumentCallbackUnitTests {
Target target = callback.doWith(new Document("_id", new Document("foo", "bar")).append("foo", "foobar"));
assertThat(target.id, is(nullValue()));
assertThat(target.foo, is("foobar"));
assertThat(target.id).isNull();
assertThat(target.foo).isEqualTo("foobar");
}
@Test
@@ -89,8 +89,8 @@ public class UnwrapAndReadDocumentCallbackUnitTests {
Target target = callback.doWith(new Document("_id", "bar").append("foo", "foo"));
assertThat(target.id, is("bar"));
assertThat(target.foo, is("foo"));
assertThat(target.id).isEqualTo("bar");
assertThat(target.foo).isEqualTo("foo");
}
static class Target {

View File

@@ -15,12 +15,11 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.domain.Sort.Direction.*;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
import static org.springframework.data.mongodb.core.aggregation.Fields.*;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.test.util.IsBsonObject.*;
import static org.springframework.data.mongodb.test.util.Assertions.*;
import lombok.Builder;
@@ -40,7 +39,6 @@ import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDateTime;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -48,6 +46,7 @@ import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.dao.DataAccessException;
@@ -521,7 +520,7 @@ public class AggregationTests {
/*
//complex mongodb aggregation framework example from
https://docs.mongodb.org/manual/tutorial/aggregation-examples/#largest-and-smallest-cities-by-state
db.zipcodes.aggregate(
{
$group: {
@@ -1553,7 +1552,7 @@ public class AggregationTests {
Document firstItem = mappedResults.get(0);
assertThat(firstItem).containsEntry("_id", "u1");
Assert.assertThat(firstItem, isBsonObject().containing("linkedPerson.[0].firstname", "u1"));
assertThat(firstItem).containsEntry("linkedPerson.[0].firstname", "u1");
}
@Test // DATAMONGO-1326
@@ -1574,7 +1573,7 @@ public class AggregationTests {
Document firstItem = mappedResults.get(0);
assertThat(firstItem).containsEntry("foreignKey", "u1");
Assert.assertThat(firstItem, isBsonObject().containing("linkedPerson.[0].firstname", "u1"));
assertThat(firstItem).containsEntry("linkedPerson.[0].firstname", "u1");
}
@Test // DATAMONGO-1418, DATAMONGO-1824
@@ -1784,7 +1783,8 @@ public class AggregationTests {
assertThat(object).containsEntry("name", "Andrew").containsEntry("reportsTo", "Eliot");
assertThat(list).containsOnly(
new Document("_id", 2).append("name", "Eliot").append("reportsTo", "Dev").append("depth", 0L).append("_class", Employee.class.getName()),
new Document("_id", 2).append("name", "Eliot").append("reportsTo", "Dev").append("depth", 0L).append("_class",
Employee.class.getName()),
new Document("_id", 1).append("name", "Dev").append("depth", 1L).append("_class", Employee.class.getName()));
}
@@ -1812,7 +1812,7 @@ public class AggregationTests {
// { "_id" : 0 , "count" : 1 , "titles" : [ "Dancer"] , "sum" : 760.4000000000001}
Document bound0 = result.getMappedResults().get(0);
Assert.assertThat(bound0, isBsonObject().containing("count", 1).containing("titles.[0]", "Dancer"));
assertThat(bound0).containsEntry("count", 1).containsEntry("titles.[0]", "Dancer");
assertThat((Double) bound0.get("sum")).isCloseTo(760.40, Offset.offset(0.1D));
// { "_id" : 100 , "count" : 2 , "titles" : [ "The Pillars of Society" , "The Great Wave off Kanagawa"] , "sum" :
@@ -1846,8 +1846,8 @@ public class AggregationTests {
// { "min" : 680.0 , "max" : 820.0 , "count" : 1 , "titles" : [ "Dancer"] , "sum" : 760.4000000000001}
Document bound0 = result.getMappedResults().get(0);
Assert.assertThat(bound0, isBsonObject().containing("count", 1).containing("titles.[0]", "Dancer")
.containing("min", 680.0).containing("max"));
assertThat(bound0).containsEntry("count", 1).containsEntry("titles.[0]", "Dancer").containsEntry("min", 680.0)
.containsKey("max");
// { "min" : 820.0 , "max" : 1800.0 , "count" : 1 , "titles" : [ "The Great Wave off Kanagawa"] , "sum" : 1673.0}
Document bound1 = result.getMappedResults().get(1);

View File

@@ -15,15 +15,14 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.hamcrest.core.Is.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.core.DocumentTestUtils.getAsDocument;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.mongodb.core.DocumentTestUtils.*;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
import org.junit.Test;
import org.springframework.data.mongodb.core.aggregation.BucketAutoOperation.Granularities;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.mongodb.core.aggregation.BucketAutoOperation.Granularities;
/**
* Unit tests for {@link BucketAutoOperation}.
@@ -50,8 +49,8 @@ public class BucketAutoOperationUnitTests {
.andOutput("title").push().as("titles");
Document agg = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(extractOutput(agg), is(Document.parse(
"{ \"grossSalesPrice\" : { \"$multiply\" : [ { \"$add\" : [ \"$netPrice\" , \"$surCharge\"]} , \"$taxrate\" , 2]} , \"titles\" : { $push: \"$title\" } }}")));
assertThat(extractOutput(agg)).isEqualTo(Document.parse(
"{ \"grossSalesPrice\" : { \"$multiply\" : [ { \"$add\" : [ \"$netPrice\" , \"$surCharge\"]} , \"$taxrate\" , 2]} , \"titles\" : { $push: \"$title\" } }}"));
}
@Test(expected = IllegalStateException.class) // DATAMONGO-1552
@@ -66,7 +65,7 @@ public class BucketAutoOperationUnitTests {
.andOutputCount().as("titles");
Document agg = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(extractOutput(agg), is(Document.parse("{ titles : { $sum: 1 } }")));
assertThat(extractOutput(agg)).isEqualTo(Document.parse("{ titles : { $sum: 1 } }"));
}
@Test // DATAMONGO-1552
@@ -74,7 +73,7 @@ public class BucketAutoOperationUnitTests {
Document agg = bucketAuto("field", 1).withBuckets(5).toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(agg, is(Document.parse("{ $bucketAuto: { groupBy: \"$field\", buckets: 5 } }")));
assertThat(agg).isEqualTo(Document.parse("{ $bucketAuto: { groupBy: \"$field\", buckets: 5 } }"));
}
@Test // DATAMONGO-1552
@@ -84,7 +83,8 @@ public class BucketAutoOperationUnitTests {
.withGranularity(Granularities.E24) //
.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(agg, is(Document.parse("{ $bucketAuto: { buckets: 1, granularity: \"E24\", groupBy: \"$field\" } }")));
assertThat(agg)
.isEqualTo(Document.parse("{ $bucketAuto: { buckets: 1, granularity: \"E24\", groupBy: \"$field\" } }"));
}
@Test // DATAMONGO-1552
@@ -94,7 +94,7 @@ public class BucketAutoOperationUnitTests {
.andOutput("score").sum().as("cummulated_score");
Document agg = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(extractOutput(agg), is(Document.parse("{ cummulated_score : { $sum: \"$score\" } }")));
assertThat(extractOutput(agg)).isEqualTo(Document.parse("{ cummulated_score : { $sum: \"$score\" } }"));
}
@Test // DATAMONGO-1552
@@ -104,8 +104,8 @@ public class BucketAutoOperationUnitTests {
.andOutputExpression("netPrice + tax").apply("$multiply", 5).as("total");
Document agg = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(extractOutput(agg),
is(Document.parse("{ total : { $multiply: [ {$add : [\"$netPrice\", \"$tax\"]}, 5] } }")));
assertThat(extractOutput(agg))
.isEqualTo(Document.parse("{ total : { $multiply: [ {$add : [\"$netPrice\", \"$tax\"]}, 5] } }"));
}
private static Document extractOutput(Document fromBucketClause) {

View File

@@ -15,14 +15,11 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
import org.junit.Test;
import org.bson.Document;
import org.junit.Test;
/**
* Unit tests for {@link BucketOperation}.
@@ -44,8 +41,8 @@ public class BucketOperationUnitTests {
.andOutput("title").push().as("titles");
Document dbObject = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(extractOutput(dbObject), is(Document.parse(
"{ \"grossSalesPrice\" : { \"$multiply\" : [ { \"$add\" : [ \"$netPrice\" , \"$surCharge\"]} , \"$taxrate\" , 2]} , \"titles\" : { $push: \"$title\" } }}")));
assertThat(extractOutput(dbObject)).isEqualTo(Document.parse(
"{ \"grossSalesPrice\" : { \"$multiply\" : [ { \"$add\" : [ \"$netPrice\" , \"$surCharge\"]} , \"$taxrate\" , 2]} , \"titles\" : { $push: \"$title\" } }}"));
}
@Test(expected = IllegalStateException.class) // DATAMONGO-1552
@@ -60,7 +57,7 @@ public class BucketOperationUnitTests {
.andOutputCount().as("titles");
Document agg = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(extractOutput(agg), is(Document.parse("{ titles : { $sum: 1 } }")));
assertThat(extractOutput(agg)).isEqualTo(Document.parse("{ titles : { $sum: 1 } }"));
}
@Test // DATAMONGO-1552
@@ -70,8 +67,8 @@ public class BucketOperationUnitTests {
.andOutput(ArithmeticOperators.valueOf("quizzes").sum()).as("quizTotal") //
.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(agg, is(Document.parse(
"{ $bucket: { groupBy: \"$field\", boundaries: [], output : { quizTotal: { $sum: \"$quizzes\"} } } }")));
assertThat(agg).isEqualTo(Document
.parse("{ $bucket: { groupBy: \"$field\", boundaries: [], output : { quizTotal: { $sum: \"$quizzes\"} } } }"));
}
@Test // DATAMONGO-1552
@@ -79,8 +76,8 @@ public class BucketOperationUnitTests {
Document agg = bucket("field").withDefaultBucket("default bucket").toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(agg,
is(Document.parse("{ $bucket: { groupBy: \"$field\", boundaries: [], default: \"default bucket\" } }")));
assertThat(agg).isEqualTo(
Document.parse("{ $bucket: { groupBy: \"$field\", boundaries: [], default: \"default bucket\" } }"));
}
@Test // DATAMONGO-1552
@@ -91,8 +88,8 @@ public class BucketOperationUnitTests {
.withBoundaries(0) //
.withBoundaries(10, 20).toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(agg,
is(Document.parse("{ $bucket: { boundaries: [0, 10, 20], default: \"default bucket\", groupBy: \"$field\" } }")));
assertThat(agg).isEqualTo(
Document.parse("{ $bucket: { boundaries: [0, 10, 20], default: \"default bucket\", groupBy: \"$field\" } }"));
}
@Test // DATAMONGO-1552
@@ -102,7 +99,7 @@ public class BucketOperationUnitTests {
.andOutput("score").sum().as("cummulated_score");
Document agg = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(extractOutput(agg), is(Document.parse("{ cummulated_score : { $sum: \"$score\" } }")));
assertThat(extractOutput(agg)).isEqualTo(Document.parse("{ cummulated_score : { $sum: \"$score\" } }"));
}
@Test // DATAMONGO-1552
@@ -112,7 +109,7 @@ public class BucketOperationUnitTests {
.andOutput("score").sum(4).as("cummulated_score");
Document agg = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(extractOutput(agg), is(Document.parse("{ cummulated_score : { $sum: 4 } }")));
assertThat(extractOutput(agg)).isEqualTo(Document.parse("{ cummulated_score : { $sum: 4 } }"));
}
@Test // DATAMONGO-1552
@@ -122,7 +119,7 @@ public class BucketOperationUnitTests {
.andOutput("score").avg().as("average");
Document agg = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(extractOutput(agg), is(Document.parse("{ average : { $avg: \"$score\" } }")));
assertThat(extractOutput(agg)).isEqualTo(Document.parse("{ average : { $avg: \"$score\" } }"));
}
@Test // DATAMONGO-1552
@@ -132,7 +129,7 @@ public class BucketOperationUnitTests {
.andOutput("title").first().as("first_title");
Document agg = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(extractOutput(agg), is(Document.parse("{ first_title : { $first: \"$title\" } }")));
assertThat(extractOutput(agg)).isEqualTo(Document.parse("{ first_title : { $first: \"$title\" } }"));
}
@Test // DATAMONGO-1552
@@ -142,7 +139,7 @@ public class BucketOperationUnitTests {
.andOutput("title").last().as("last_title");
Document agg = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(extractOutput(agg), is(Document.parse("{ last_title : { $last: \"$title\" } }")));
assertThat(extractOutput(agg)).isEqualTo(Document.parse("{ last_title : { $last: \"$title\" } }"));
}
@Test // DATAMONGO-1552
@@ -152,7 +149,7 @@ public class BucketOperationUnitTests {
.andOutput("score").min().as("min_score");
Document agg = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(extractOutput(agg), is(Document.parse("{ min_score : { $min: \"$score\" } }")));
assertThat(extractOutput(agg)).isEqualTo(Document.parse("{ min_score : { $min: \"$score\" } }"));
}
@Test // DATAMONGO-1552
@@ -162,7 +159,7 @@ public class BucketOperationUnitTests {
.andOutput("title").push().as("titles");
Document agg = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(extractOutput(agg), is(Document.parse("{ titles : { $push: \"$title\" } }")));
assertThat(extractOutput(agg)).isEqualTo(Document.parse("{ titles : { $push: \"$title\" } }"));
}
@Test // DATAMONGO-1552
@@ -172,7 +169,7 @@ public class BucketOperationUnitTests {
.andOutput("title").addToSet().as("titles");
Document agg = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(extractOutput(agg), is(Document.parse("{ titles : { $addToSet: \"$title\" } }")));
assertThat(extractOutput(agg)).isEqualTo(Document.parse("{ titles : { $addToSet: \"$title\" } }"));
}
@Test // DATAMONGO-1552
@@ -182,7 +179,8 @@ public class BucketOperationUnitTests {
.andOutputExpression("netPrice + tax").sum().as("total");
Document agg = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(extractOutput(agg), is(Document.parse("{ total : { $sum: { $add : [\"$netPrice\", \"$tax\"]} } }")));
assertThat(extractOutput(agg))
.isEqualTo(Document.parse("{ total : { $sum: { $add : [\"$netPrice\", \"$tax\"]} } }"));
}
@Test // DATAMONGO-1552
@@ -192,8 +190,8 @@ public class BucketOperationUnitTests {
.andOutputExpression("netPrice + tax").apply("$multiply", 5).as("total");
Document agg = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(extractOutput(agg),
is(Document.parse("{ total : { $multiply: [ {$add : [\"$netPrice\", \"$tax\"]}, 5] } }")));
assertThat(extractOutput(agg))
.isEqualTo(Document.parse("{ total : { $multiply: [ {$add : [\"$netPrice\", \"$tax\"]}, 5] } }"));
}
@Test // DATAMONGO-1552
@@ -201,8 +199,8 @@ public class BucketOperationUnitTests {
BucketOperation operation = bucket("field");
assertThat(operation.getFields().exposesSingleFieldOnly(), is(true));
assertThat(operation.getFields().getField("count"), is(notNullValue()));
assertThat(operation.getFields().exposesSingleFieldOnly()).isTrue();
assertThat(operation.getFields().getField("count")).isNotNull();
}
private static Document extractOutput(Document fromBucketClause) {

View File

@@ -15,9 +15,8 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.core.aggregation.ConditionalOperators.Cond.*;
import static org.springframework.data.mongodb.test.util.IsBsonObject.*;
import static org.springframework.data.mongodb.test.util.Assertions.*;
import java.util.Arrays;
@@ -65,7 +64,7 @@ public class CondExpressionUnitTests {
.append("then", "bright") //
.append("else", "dark");
assertThat(document, isBsonObject().containing("$cond", expectedCondition));
assertThat(document).containsEntry("$cond", expectedCondition);
}
@Test // DATAMONGO-861, DATAMONGO-1542
@@ -80,7 +79,7 @@ public class CondExpressionUnitTests {
.append("then", "bright") //
.append("else", "dark");
assertThat(document, isBsonObject().containing("$cond", expectedCondition));
assertThat(document).containsEntry("$cond", expectedCondition);
}
@Test // DATAMONGO-861
@@ -102,7 +101,7 @@ public class CondExpressionUnitTests {
.append("then", "bright") //
.append("else", "$dark-field");
assertThat(document, isBsonObject().containing("$cond", expectedCondition));
assertThat(document).containsEntry("$cond", expectedCondition);
}
@Test // DATAMONGO-861, DATAMONGO-1542
@@ -122,7 +121,7 @@ public class CondExpressionUnitTests {
.append("then", "bright") //
.append("else", "dark");
assertThat(document, isBsonObject().containing("$cond", expectedCondition));
assertThat(document).containsEntry("$cond", expectedCondition);
}
@Test // DATAMONGO-861, DATAMONGO-1542
@@ -150,7 +149,7 @@ public class CondExpressionUnitTests {
.append("then", "very-dark") //
.append("else", "not-so-dark");
assertThat(document, isBsonObject().containing("$cond.then.$cond", trueCondition));
assertThat(document, isBsonObject().containing("$cond.else.$cond", falseCondition));
assertThat(document).containsEntry("$cond.then.$cond", trueCondition);
assertThat(document).containsEntry("$cond.else.$cond", falseCondition);
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.bson.Document;
import org.junit.Test;
@@ -37,7 +36,8 @@ public class CountOperationUnitTests {
public void shouldRenderCorrectly() {
CountOperation countOperation = new CountOperation("field");
assertThat(countOperation.toDocument(Aggregation.DEFAULT_CONTEXT), is(Document.parse("{$count : \"field\" }")));
assertThat(countOperation.toDocument(Aggregation.DEFAULT_CONTEXT))
.isEqualTo(Document.parse("{$count : \"field\" }"));
}
@Test // DATAMONGO-1549
@@ -45,8 +45,8 @@ public class CountOperationUnitTests {
CountOperation countOperation = new CountOperation("field");
assertThat(countOperation.getFields().exposesNoFields(), is(false));
assertThat(countOperation.getFields().exposesSingleFieldOnly(), is(true));
assertThat(countOperation.getFields().getField("field"), notNullValue());
assertThat(countOperation.getFields().exposesNoFields()).isFalse();
assertThat(countOperation.getFields().exposesSingleFieldOnly()).isTrue();
assertThat(countOperation.getFields().getField("field")).isNotNull();
}
}

View File

@@ -15,10 +15,10 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.data.mongodb.core.aggregation.ExposedFields.ExposedField;
/**
@@ -48,9 +48,9 @@ public class ExposedFieldsUnitTests {
public void exposesSingleField() {
ExposedFields fields = ExposedFields.synthetic(Fields.fields("foo"));
assertThat(fields.exposesSingleFieldOnly(), is(true));
assertThat(fields.exposesSingleFieldOnly()).isTrue();
fields = fields.and(new ExposedField("bar", true));
assertThat(fields.exposesSingleFieldOnly(), is(false));
assertThat(fields.exposesSingleFieldOnly()).isFalse();
}
}

View File

@@ -15,13 +15,12 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
import static org.springframework.data.mongodb.test.util.Assertions.assertThat;
import static org.springframework.data.mongodb.test.util.Assertions.*;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.mongodb.core.query.Criteria;
/**
@@ -61,7 +60,7 @@ public class FacetOperationUnitTests {
Document agg = facetOperation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(agg, is(Document.parse("{ $facet: { } }")));
assertThat(agg).isEqualTo(Document.parse("{ $facet: { } }"));
}
@Test(expected = IllegalArgumentException.class) // DATAMONGO-1552

View File

@@ -15,15 +15,14 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.mongodb.core.aggregation.Fields.*;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.data.mongodb.core.aggregation.Fields.AggregationField;
import org.springframework.data.mongodb.core.aggregation.Fields.*;
/**
* Unit tests for {@link Fields}.
@@ -76,8 +75,8 @@ public class FieldsUnitTests {
AggregationField reference = new AggregationField("foo");
Fields fields = Fields.from(reference);
assertThat(fields, is(Matchers.<Field> iterableWithSize(1)));
assertThat(fields, hasItem(reference));
assertThat(fields).hasSize(1);
assertThat(fields).contains(reference);
}
@Test
@@ -90,7 +89,7 @@ public class FieldsUnitTests {
Fields fields = fields("a", "b").and("c").and("d", "e");
assertThat(fields, is(Matchers.<Field> iterableWithSize(4)));
assertThat(fields).hasSize(4);
verify(fields.getField("a"), "a", null);
verify(fields.getField("b"), "b", null);
@@ -109,8 +108,8 @@ public class FieldsUnitTests {
@Test // DATAMONGO-774
public void stripsLeadingDollarsFromName() {
assertThat(Fields.field("$name").getName(), is("name"));
assertThat(Fields.field("$$$$name").getName(), is("name"));
assertThat(Fields.field("$name").getName()).isEqualTo("name");
assertThat(Fields.field("$$$$name").getName()).isEqualTo("name");
}
@Test(expected = IllegalArgumentException.class) // DATAMONGO-774
@@ -121,14 +120,14 @@ public class FieldsUnitTests {
@Test // DATAMONGO-774
public void stripsLeadingDollarsFromTarget() {
assertThat(Fields.field("$target").getTarget(), is("target"));
assertThat(Fields.field("$$$$target").getTarget(), is("target"));
assertThat(Fields.field("$target").getTarget()).isEqualTo("target");
assertThat(Fields.field("$$$$target").getTarget()).isEqualTo("target");
}
private static void verify(Field field, String name, String target) {
assertThat(field, is(notNullValue()));
assertThat(field.getName(), is(name));
assertThat(field.getTarget(), is(target != null ? target : name));
assertThat(field).isNotNull();
assertThat(field.getName()).isEqualTo(name);
assertThat(field.getTarget()).isEqualTo(target != null ? target : name);
}
}

View File

@@ -15,9 +15,8 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.hamcrest.core.Is.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.core.aggregation.ArrayOperators.Filter.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.mongodb.core.aggregation.ArrayOperators.Filter.filter;
import java.util.Arrays;
import java.util.List;
@@ -28,6 +27,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.DocumentTestUtils;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
@@ -75,7 +75,7 @@ public class FilterExpressionUnitTests {
"cond: { $gte: [ \"$$item.price\", 100 ] }" + //
"}");
assertThat($filter, is(new Document(expected)));
assertThat($filter).isEqualTo(new Document(expected));
}
@Test // DATAMONGO-1491
@@ -97,7 +97,7 @@ public class FilterExpressionUnitTests {
"cond: { $gte: [ \"$$item.price\", 100 ] }" + //
"}");
assertThat($filter, is(expected));
assertThat($filter).isEqualTo(expected);
}
@Test // DATAMONGO-1491
@@ -120,7 +120,7 @@ public class FilterExpressionUnitTests {
"cond: { $gte: [ \"$$num\", 3 ] }" + //
"}");
assertThat($filter, is(expected));
assertThat($filter).isEqualTo(expected);
}
static class Sales {

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.mongodb.core.aggregation.AggregationFunctionExpressions.*;
import static org.springframework.data.mongodb.core.aggregation.Fields.*;
@@ -24,6 +23,7 @@ import java.util.Arrays;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.mongodb.core.DocumentTestUtils;
import org.springframework.data.mongodb.core.query.Criteria;
@@ -48,9 +48,9 @@ public class GroupOperationUnitTests {
ExposedFields fields = operation.getFields();
Document groupClause = extractDocumentFromGroupOperation(operation);
assertThat(fields.exposesSingleFieldOnly(), is(true));
assertThat(fields.exposesNoFields(), is(false));
assertThat(groupClause.get(UNDERSCORE_ID), is(nullValue()));
assertThat(fields.exposesSingleFieldOnly()).isTrue();
assertThat(fields.exposesNoFields()).isFalse();
assertThat(groupClause.get(UNDERSCORE_ID)).isNull();
}
@Test // DATAMONGO-759
@@ -60,11 +60,11 @@ public class GroupOperationUnitTests {
ExposedFields fields = operation.getFields();
Document groupClause = extractDocumentFromGroupOperation(operation);
assertThat(fields.exposesSingleFieldOnly(), is(false));
assertThat(fields.exposesNoFields(), is(false));
assertThat(groupClause.get(UNDERSCORE_ID), is(nullValue()));
assertThat((Document) groupClause.get("cnt"), is(new Document("$sum", 1)));
assertThat((Document) groupClause.get("foo"), is(new Document("$last", "$foo")));
assertThat(fields.exposesSingleFieldOnly()).isFalse();
assertThat(fields.exposesNoFields()).isFalse();
assertThat(groupClause.get(UNDERSCORE_ID)).isNull();
assertThat((Document) groupClause.get("cnt")).isEqualTo(new Document("$sum", 1));
assertThat((Document) groupClause.get("foo")).isEqualTo(new Document("$last", "$foo"));
}
@Test
@@ -74,7 +74,7 @@ public class GroupOperationUnitTests {
Document groupClause = extractDocumentFromGroupOperation(operation);
assertThat(groupClause.get(UNDERSCORE_ID), is((Object) "$a"));
assertThat(groupClause.get(UNDERSCORE_ID)).isEqualTo((Object) "$a");
}
@Test
@@ -85,8 +85,8 @@ public class GroupOperationUnitTests {
Document groupClause = extractDocumentFromGroupOperation(operation);
Document idClause = DocumentTestUtils.getAsDocument(groupClause, UNDERSCORE_ID);
assertThat(idClause.get("a"), is((Object) "$a"));
assertThat(idClause.get("b"), is((Object) "$c"));
assertThat(idClause.get("a")).isEqualTo((Object) "$a");
assertThat(idClause.get("b")).isEqualTo((Object) "$c");
}
@Test
@@ -97,7 +97,7 @@ public class GroupOperationUnitTests {
Document groupClause = extractDocumentFromGroupOperation(groupOperation);
Document eOp = DocumentTestUtils.getAsDocument(groupClause, "e");
assertThat(eOp, is((Document) new Document("$sum", "$e")));
assertThat(eOp).isEqualTo((Document) new Document("$sum", "$e"));
}
@Test
@@ -108,7 +108,7 @@ public class GroupOperationUnitTests {
Document groupClause = extractDocumentFromGroupOperation(groupOperation);
Document eOp = DocumentTestUtils.getAsDocument(groupClause, "ee");
assertThat(eOp, is((Document) new Document("$sum", "$e")));
assertThat(eOp).isEqualTo((Document) new Document("$sum", "$e"));
}
@Test
@@ -119,7 +119,7 @@ public class GroupOperationUnitTests {
Document groupClause = extractDocumentFromGroupOperation(groupOperation);
Document eOp = DocumentTestUtils.getAsDocument(groupClause, "count");
assertThat(eOp, is((Document) new Document("$sum", 1)));
assertThat(eOp).isEqualTo((Document) new Document("$sum", 1));
}
@Test
@@ -131,10 +131,10 @@ public class GroupOperationUnitTests {
Document groupClause = extractDocumentFromGroupOperation(groupOperation);
Document sum = DocumentTestUtils.getAsDocument(groupClause, "sum");
assertThat(sum, is((Document) new Document("$sum", "$e")));
assertThat(sum).isEqualTo((Document) new Document("$sum", "$e"));
Document min = DocumentTestUtils.getAsDocument(groupClause, "min");
assertThat(min, is((Document) new Document("$min", "$e")));
assertThat(min).isEqualTo((Document) new Document("$min", "$e"));
}
@Test
@@ -145,7 +145,7 @@ public class GroupOperationUnitTests {
Document groupClause = extractDocumentFromGroupOperation(groupOperation);
Document push = DocumentTestUtils.getAsDocument(groupClause, "x");
assertThat(push, is((Document) new Document("$push", 1)));
assertThat(push).isEqualTo((Document) new Document("$push", 1));
}
@Test
@@ -156,7 +156,7 @@ public class GroupOperationUnitTests {
Document groupClause = extractDocumentFromGroupOperation(groupOperation);
Document push = DocumentTestUtils.getAsDocument(groupClause, "x");
assertThat(push, is((Document) new Document("$push", "$ref")));
assertThat(push).isEqualTo((Document) new Document("$push", "$ref"));
}
@Test
@@ -167,7 +167,7 @@ public class GroupOperationUnitTests {
Document groupClause = extractDocumentFromGroupOperation(groupOperation);
Document push = DocumentTestUtils.getAsDocument(groupClause, "x");
assertThat(push, is((Document) new Document("$addToSet", "$ref")));
assertThat(push).isEqualTo((Document) new Document("$addToSet", "$ref"));
}
@Test
@@ -178,7 +178,7 @@ public class GroupOperationUnitTests {
Document groupClause = extractDocumentFromGroupOperation(groupOperation);
Document push = DocumentTestUtils.getAsDocument(groupClause, "x");
assertThat(push, is((Document) new Document("$addToSet", 42)));
assertThat(push).isEqualTo((Document) new Document("$addToSet", 42));
}
@Test // DATAMONGO-979
@@ -192,7 +192,7 @@ public class GroupOperationUnitTests {
Document groupClause = extractDocumentFromGroupOperation(groupOperation);
Document tagsCount = DocumentTestUtils.getAsDocument(groupClause, "tags_count");
assertThat(tagsCount.get("$first"), is((Object) new Document("$size", Arrays.asList("$tags"))));
assertThat(tagsCount.get("$first")).isEqualTo((Object) new Document("$size", Arrays.asList("$tags")));
}
@Test // DATAMONGO-1327
@@ -203,7 +203,7 @@ public class GroupOperationUnitTests {
Document groupClause = extractDocumentFromGroupOperation(groupOperation);
Document push = DocumentTestUtils.getAsDocument(groupClause, "fieldStdDevSamp");
assertThat(push, is(new Document("$stdDevSamp", "$field")));
assertThat(push).isEqualTo(new Document("$stdDevSamp", "$field"));
}
@Test // DATAMONGO-1327
@@ -214,7 +214,7 @@ public class GroupOperationUnitTests {
Document groupClause = extractDocumentFromGroupOperation(groupOperation);
Document push = DocumentTestUtils.getAsDocument(groupClause, "fieldStdDevPop");
assertThat(push, is(new Document("$stdDevPop", "$field")));
assertThat(push).isEqualTo(new Document("$stdDevPop", "$field"));
}
@Test // DATAMONGO-1784
@@ -231,8 +231,8 @@ public class GroupOperationUnitTests {
Document groupClause = extractDocumentFromGroupOperation(groupOperation);
Document foobar = DocumentTestUtils.getAsDocument(groupClause, "foobar");
assertThat(foobar.get("$sum"), is(new Document("$cond",
new Document("if", new Document("$eq", Arrays.asList("$foo", "bar"))).append("then", 1).append("else", -1))));
assertThat(foobar.get("$sum")).isEqualTo(new Document("$cond",
new Document("if", new Document("$eq", Arrays.asList("$foo", "bar"))).append("then", 1).append("else", -1)));
}
@Test(expected = IllegalArgumentException.class) // DATAMONGO-1784

View File

@@ -15,12 +15,11 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.test.util.IsBsonObject.*;
import static org.assertj.core.api.Assertions.*;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.mongodb.core.DocumentTestUtils;
/**
@@ -59,11 +58,10 @@ public class LookupOperationUnitTests {
Document lookupClause = extractDocumentFromLookupOperation(lookupOperation);
assertThat(lookupClause,
isBsonObject().containing("from", "a") //
.containing("localField", "b") //
.containing("foreignField", "c") //
.containing("as", "d"));
assertThat(lookupClause).containsEntry("from", "a") //
.containsEntry("localField", "b") //
.containsEntry("foreignField", "c") //
.containsEntry("as", "d");
}
@Test // DATAMONGO-1326
@@ -71,9 +69,9 @@ public class LookupOperationUnitTests {
LookupOperation lookupOperation = Aggregation.lookup("a", "b", "c", "d");
assertThat(lookupOperation.getFields().exposesNoFields(), is(false));
assertThat(lookupOperation.getFields().exposesSingleFieldOnly(), is(true));
assertThat(lookupOperation.getFields().getField("d"), notNullValue());
assertThat(lookupOperation.getFields().exposesNoFields()).isFalse();
assertThat(lookupOperation.getFields().exposesSingleFieldOnly()).isTrue();
assertThat(lookupOperation.getFields().getField("d")).isNotNull();
}
private Document extractDocumentFromLookupOperation(LookupOperation lookupOperation) {
@@ -110,11 +108,10 @@ public class LookupOperationUnitTests {
Document lookupClause = extractDocumentFromLookupOperation(lookupOperation);
assertThat(lookupClause,
isBsonObject().containing("from", "a") //
.containing("localField", "b") //
.containing("foreignField", "c") //
.containing("as", "d"));
assertThat(lookupClause).containsEntry("from", "a") //
.containsEntry("localField", "b") //
.containsEntry("foreignField", "c") //
.containsEntry("as", "d");
}
@Test // DATAMONGO-1326
@@ -122,8 +119,8 @@ public class LookupOperationUnitTests {
LookupOperation lookupOperation = LookupOperation.newLookup().from("a").localField("b").foreignField("c").as("d");
assertThat(lookupOperation.getFields().exposesNoFields(), is(false));
assertThat(lookupOperation.getFields().exposesSingleFieldOnly(), is(true));
assertThat(lookupOperation.getFields().getField("d"), notNullValue());
assertThat(lookupOperation.getFields().exposesNoFields()).isFalse();
assertThat(lookupOperation.getFields().exposesSingleFieldOnly()).isTrue();
assertThat(lookupOperation.getFields().getField("d")).isNotNull();
}
}

View File

@@ -15,11 +15,11 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.mongodb.core.aggregation.ReplaceRootOperation.ReplaceRootDocumentOperation;
/**
@@ -46,7 +46,7 @@ public class ReplaceRootOperationUnitTests {
.withDocument(new Document("hello", "world"));
Document dbObject = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(dbObject, is(Document.parse("{ $replaceRoot : { newRoot: { hello: \"world\" } } }")));
assertThat(dbObject).isEqualTo(Document.parse("{ $replaceRoot : { newRoot: { hello: \"world\" } } }"));
}
@Test // DATAMONGO-1550
@@ -59,8 +59,8 @@ public class ReplaceRootOperationUnitTests {
Document dbObject = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(dbObject, is(Document.parse("{ $replaceRoot : { newRoot : { "
+ "$map : { input : \"$array\" , as : \"element\" , in : { $multiply : [ \"$$element\" , 10]} } " + "} } }")));
assertThat(dbObject).isEqualTo(Document.parse("{ $replaceRoot : { newRoot : { "
+ "$map : { input : \"$array\" , as : \"element\" , in : { $multiply : [ \"$$element\" , 10]} } " + "} } }"));
}
@Test // DATAMONGO-1550
@@ -72,8 +72,8 @@ public class ReplaceRootOperationUnitTests {
Document dbObject = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(dbObject, is(Document
.parse("{ $replaceRoot : { newRoot: { key: \"value\", multiply: { $multiply : [ \"$$element\" , 10]} } } }")));
assertThat(dbObject).isEqualTo(Document
.parse("{ $replaceRoot : { newRoot: { key: \"value\", multiply: { $multiply : [ \"$$element\" , 10]} } } }"));
}
@Test // DATAMONGO-1550
@@ -87,7 +87,8 @@ public class ReplaceRootOperationUnitTests {
Document dbObject = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(dbObject, is(Document.parse("{ $replaceRoot : { newRoot: { key: \"override\", key2: \"value2\"} } } }")));
assertThat(dbObject)
.isEqualTo(Document.parse("{ $replaceRoot : { newRoot: { key: \"override\", key2: \"value2\"} } } }"));
}
@Test // DATAMONGO-1550
@@ -95,7 +96,7 @@ public class ReplaceRootOperationUnitTests {
ReplaceRootOperation operation = new ReplaceRootOperation(Fields.field("field"));
assertThat(operation.getFields().exposesNoFields(), is(true));
assertThat(operation.getFields().exposesSingleFieldOnly(), is(false));
assertThat(operation.getFields().exposesNoFields()).isTrue();
assertThat(operation.getFields().exposesSingleFieldOnly()).isFalse();
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.bson.Document;
import org.junit.Test;
@@ -50,10 +49,10 @@ public class SampleOperationUnitTests {
Document sampleOperationDocument = sampleOperation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertNotNull(sampleOperationDocument.get(OP));
assertThat(sampleOperationDocument.get(OP), is(instanceOf(Document.class)));
assertThat(sampleOperationDocument.get(OP)).isNotNull();
assertThat(sampleOperationDocument.get(OP)).isInstanceOf(Document.class);
Document sampleSizeDocument = sampleOperationDocument.get(OP, Document.class);
assertEquals(sampleSize, sampleSizeDocument.get(SIZE));
assertThat(sampleSizeDocument.get(SIZE)).isEqualTo(sampleSize);
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.bson.Document;
import org.junit.Test;
@@ -41,6 +40,6 @@ public class SkipOperationUnitTests {
SkipOperation operation = new SkipOperation(10L);
Document document = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(document.get(OP), is((Object) 10L));
assertThat(document.get(OP)).isEqualTo((Object) 10L);
}
}

View File

@@ -15,12 +15,12 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.mongodb.core.DocumentTestUtils.*;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
@@ -39,8 +39,8 @@ public class SortOperationUnitTests {
Document result = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
Document sortValue = getAsDocument(result, "$sort");
assertThat(sortValue, is(notNullValue()));
assertThat(sortValue.get("foobar"), is((Object) 1));
assertThat(sortValue).isNotNull();
assertThat(sortValue.get("foobar")).isEqualTo((Object) 1);
}
@Test
@@ -50,7 +50,7 @@ public class SortOperationUnitTests {
Document result = operation.toDocument(Aggregation.DEFAULT_CONTEXT);
Document sortValue = getAsDocument(result, "$sort");
assertThat(sortValue, is(notNullValue()));
assertThat(sortValue.get("foobar"), is((Object) (0 - 1)));
assertThat(sortValue).isNotNull();
assertThat(sortValue.get("foobar")).isEqualTo((Object) (0 - 1));
}
}

View File

@@ -15,14 +15,14 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mapping.MappingException;
import org.springframework.data.mongodb.MongoDbFactory;
@@ -62,8 +62,8 @@ public class SpelExpressionTransformerIntegrationTests {
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, new MongoMappingContext());
TypeBasedAggregationOperationContext ctxt = new TypeBasedAggregationOperationContext(Data.class,
new MongoMappingContext(), new QueryMapper(converter));
assertThat(transformer.transform("item.primitiveIntValue", ctxt, new Object[0]).toString(),
is("$item.primitiveIntValue"));
assertThat(transformer.transform("item.primitiveIntValue", ctxt, new Object[0]).toString())
.isEqualTo("$item.primitiveIntValue");
}
@Test // DATAMONGO-774
@@ -75,6 +75,6 @@ public class SpelExpressionTransformerIntegrationTests {
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, new MongoMappingContext());
TypeBasedAggregationOperationContext ctxt = new TypeBasedAggregationOperationContext(Data.class,
new MongoMappingContext(), new QueryMapper(converter));
assertThat(transformer.transform("item.value2", ctxt, new Object[0]).toString(), is("$item.value2"));
assertThat(transformer.transform("item.value2", ctxt, new Object[0]).toString()).isEqualTo("$item.value2");
}
}

View File

@@ -15,12 +15,10 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.core.DocumentTestUtils.*;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
import static org.springframework.data.mongodb.core.aggregation.Fields.*;
import static org.springframework.data.mongodb.test.util.IsBsonObject.*;
import static org.springframework.data.mongodb.test.util.Assertions.*;
import lombok.AllArgsConstructor;
@@ -34,6 +32,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.data.annotation.Id;
@@ -77,7 +76,7 @@ public class TypeBasedAggregationOperationContextUnitTests {
@Test
public void findsSimpleReference() {
assertThat(getContext(Foo.class).getReference("bar"), is(notNullValue()));
assertThat(getContext(Foo.class).getReference("bar")).isNotNull();
}
@Test(expected = MappingException.class)
@@ -92,16 +91,17 @@ public class TypeBasedAggregationOperationContextUnitTests {
Field field = field("bar.name");
assertThat(context.getReference("bar.name"), is(notNullValue()));
assertThat(context.getReference(field), is(notNullValue()));
assertThat(context.getReference(field), is(context.getReference("bar.name")));
assertThat(context.getReference("bar.name")).isNotNull();
assertThat(context.getReference(field)).isNotNull();
assertThat(context.getReference(field)).isEqualTo(context.getReference("bar.name"));
}
@Test // DATAMONGO-806
public void aliasesIdFieldCorrectly() {
AggregationOperationContext context = getContext(Foo.class);
assertThat(context.getReference("id"), is(new DirectFieldReference(new ExposedField(field("id", "_id"), true))));
assertThat(context.getReference("id"))
.isEqualTo(new DirectFieldReference(new ExposedField(field("id", "_id"), true)));
}
@Test // DATAMONGO-912
@@ -119,7 +119,7 @@ public class TypeBasedAggregationOperationContextUnitTests {
org.bson.Document agg = newAggregation(matchStage, projectStage).toDocument("test", context);
org.bson.Document age = getValue(getValue(getPipelineElementFromAggregationAt(agg, 0), "$match"), "age");
assertThat(age, is(new org.bson.Document("v", 10)));
assertThat(age).isEqualTo(new Document("v", 10));
}
@Test // DATAMONGO-912
@@ -137,7 +137,7 @@ public class TypeBasedAggregationOperationContextUnitTests {
org.bson.Document agg = newAggregation(projectStage, matchStage).toDocument("test", context);
org.bson.Document age = getValue(getValue(getPipelineElementFromAggregationAt(agg, 1), "$match"), "age");
assertThat(age, is(new org.bson.Document("v", 10)));
assertThat(age).isEqualTo(new Document("v", 10));
}
@Test // DATAMONGO-960
@@ -151,13 +151,13 @@ public class TypeBasedAggregationOperationContextUnitTests {
org.bson.Document document = agg.toDocument("person", context);
org.bson.Document projection = getPipelineElementFromAggregationAt(document, 0);
assertThat(projection.containsKey("$project"), is(true));
assertThat(projection.containsKey("$project")).isTrue();
assertThat(projection.get("$project"), is(new Document("name", 1).append("age", 1)));
assertThat(projection.get("$project")).isEqualTo(new Document("name", 1).append("age", 1));
assertThat(document.get("allowDiskUse"), is(true));
assertThat(document.get("explain"), is(true));
assertThat(document.get("cursor"), is(new Document("foo", 1)));
assertThat(document.get("allowDiskUse")).isEqualTo(true);
assertThat(document.get("explain")).isEqualTo(true);
assertThat(document.get("cursor")).isEqualTo(new Document("foo", 1));
}
@Test // DATAMONGO-1585
@@ -171,7 +171,7 @@ public class TypeBasedAggregationOperationContextUnitTests {
Document sort = getPipelineElementFromAggregationAt(dbo, 1);
Document definition = (Document) sort.get("$sort");
assertThat(definition.get("counter"), is(equalTo(1)));
assertThat(definition.get("counter")).isEqualTo(1);
}
@Test // DATAMONGO-1586
@@ -185,9 +185,8 @@ public class TypeBasedAggregationOperationContextUnitTests {
Document dbo = agg.toDocument("person", context);
Document projection = getPipelineElementFromAggregationAt(dbo, 0);
assertThat(getAsDocument(projection, "$project"), isBsonObject() //
.containing("person_name", "$name") //
.containing("age", "$age.value"));
assertThat(getAsDocument(projection, "$project")).containsEntry("person_name", "$name") //
.containsEntry("age", "$age.value");
}
@Test // DATAMONGO-1893
@@ -200,7 +199,7 @@ public class TypeBasedAggregationOperationContextUnitTests {
Document dbo = agg.toDocument("person", context);
Document sort = getPipelineElementFromAggregationAt(dbo, 1);
assertThat(getAsDocument(sort, "$sort"), is(equalTo(new Document("age.value", 1).append("last_name", 1))));
assertThat(getAsDocument(sort, "$sort")).isEqualTo(new Document("age.value", 1).append("last_name", 1));
}
@Test // DATAMONGO-1133
@@ -215,7 +214,7 @@ public class TypeBasedAggregationOperationContextUnitTests {
org.bson.Document definition = (org.bson.Document) group.get("$group");
assertThat(definition.get("_id"), is(equalTo("$counter_name")));
assertThat(definition.get("_id")).isEqualTo("$counter_name");
}
@Test // DATAMONGO-1326, DATAMONGO-1585
@@ -231,8 +230,8 @@ public class TypeBasedAggregationOperationContextUnitTests {
org.bson.Document definition = (org.bson.Document) sort.get("$sort");
assertThat(definition.get("resourceId"), is(equalTo(1)));
assertThat(definition.get("counter_name"), is(equalTo(1)));
assertThat(definition.get("resourceId")).isEqualTo(1);
assertThat(definition.get("counter_name")).isEqualTo(1);
}
@Test // DATAMONGO-1326
@@ -247,7 +246,7 @@ public class TypeBasedAggregationOperationContextUnitTests {
org.bson.Document definition = (org.bson.Document) sort.get("$sort");
assertThat(definition.get("foreignKey"), is(equalTo(1)));
assertThat(definition.get("foreignKey")).isEqualTo(1);
}
@Test // DATAMONGO-1326
@@ -264,7 +263,7 @@ public class TypeBasedAggregationOperationContextUnitTests {
org.bson.Document definition = (org.bson.Document) group.get("$group");
org.bson.Document field = (org.bson.Document) definition.get("something_totally_different");
assertThat(field.get("$min"), is(equalTo("$lookup.otherkey")));
assertThat(field.get("$min")).isEqualTo("$lookup.otherkey");
}
@Test // DATAMONGO-1326
@@ -281,7 +280,7 @@ public class TypeBasedAggregationOperationContextUnitTests {
org.bson.Document definition = (org.bson.Document) sort.get("$sort");
assertThat(definition.get("something_totally_different"), is(equalTo(1)));
assertThat(definition.get("something_totally_different")).isEqualTo(1);
}
@Test(expected = IllegalArgumentException.class) // DATAMONGO-1326
@@ -308,14 +307,14 @@ public class TypeBasedAggregationOperationContextUnitTests {
Document document = agg.toDocument("person", context);
Document projection = getPipelineElementFromAggregationAt(document, 0);
assertThat(projection.containsKey("$project"), is(true));
assertThat(projection.containsKey("$project")).isTrue();
Document project = getValue(projection, "$project");
Document age = getValue(project, "age");
assertThat(getValue(age, "$cond"), isBsonObject().containing("then.value", 0));
assertThat(getValue(age, "$cond"), isBsonObject().containing("then._class", Age.class.getName()));
assertThat(getValue(age, "$cond"), isBsonObject().containing("else", "$age"));
assertThat((Document) getValue(age, "$cond")).containsEntry("then.value", 0);
assertThat((Document) getValue(age, "$cond")).containsEntry("then._class", Age.class.getName());
assertThat((Document) getValue(age, "$cond")).containsEntry("else", "$age");
}
/**
@@ -333,17 +332,17 @@ public class TypeBasedAggregationOperationContextUnitTests {
Document document = agg.toDocument("person", context);
Document projection = getPipelineElementFromAggregationAt(document, 0);
assertThat(projection.containsKey("$project"), is(true));
assertThat(projection.containsKey("$project")).isTrue();
Document project = getValue(projection, "$project");
Document age = getValue(project, "age");
assertThat(age, is(Document.parse(
"{ $ifNull: [ \"$age\", { \"_class\":\"org.springframework.data.mongodb.core.aggregation.TypeBasedAggregationOperationContextUnitTests$Age\", \"value\": 0} ] }")));
assertThat(age).isEqualTo(Document.parse(
"{ $ifNull: [ \"$age\", { \"_class\":\"org.springframework.data.mongodb.core.aggregation.TypeBasedAggregationOperationContextUnitTests$Age\", \"value\": 0} ] }"));
assertThat(age, isBsonObject().containing("$ifNull.[0]", "$age"));
assertThat(age, isBsonObject().containing("$ifNull.[1].value", 0));
assertThat(age, isBsonObject().containing("$ifNull.[1]._class", Age.class.getName()));
assertThat(age).containsEntry("$ifNull.[0]", "$age");
assertThat(age).containsEntry("$ifNull.[1].value", 0);
assertThat(age).containsEntry("$ifNull.[1]._class", Age.class.getName());
}
@Test // DATAMONGO-1756
@@ -354,8 +353,8 @@ public class TypeBasedAggregationOperationContextUnitTests {
Document agg = newAggregation(Wrapper.class, project().and("nested1.value1").plus("nested2.value2").as("val"))
.toDocument("collection", context);
assertThat(getPipelineElementFromAggregationAt(agg, 0).get("$project"), is(
equalTo(new Document("val", new Document("$add", Arrays.asList("$nested1.value1", "$field2.nestedValue2"))))));
assertThat(getPipelineElementFromAggregationAt(agg, 0).get("$project"))
.isEqualTo(new Document("val", new Document("$add", Arrays.asList("$nested1.value1", "$field2.nestedValue2"))));
}
@org.springframework.data.mongodb.core.mapping.Document(collection = "person")

View File

@@ -15,12 +15,11 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.test.util.IsBsonObject.*;
import static org.assertj.core.api.Assertions.*;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.mongodb.core.DocumentTestUtils;
/**
@@ -38,7 +37,7 @@ public class UnwindOperationUnitTests {
Document pipeline = unwindOperation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(pipeline, isBsonObject().containing("$unwind", "$a"));
assertThat(pipeline).containsEntry("$unwind", "$a");
}
@Test // DATAMONGO-1391
@@ -48,10 +47,9 @@ public class UnwindOperationUnitTests {
Document unwindClause = extractDocumentFromUnwindOperation(unwindOperation);
assertThat(unwindClause,
isBsonObject().containing("path", "$a").//
containing("preserveNullAndEmptyArrays", false).//
containing("includeArrayIndex", "index"));
assertThat(unwindClause).containsEntry("path", "$a").//
containsEntry("preserveNullAndEmptyArrays", false).//
containsEntry("includeArrayIndex", "index");
}
@Test // DATAMONGO-1391
@@ -59,7 +57,7 @@ public class UnwindOperationUnitTests {
UnwindOperation unwindOperation = Aggregation.unwind("a", "index");
assertThat(unwindOperation.getFields().getField("index"), is(not(nullValue())));
assertThat(unwindOperation.getFields().getField("index")).isNotNull();
}
@Test // DATAMONGO-1391
@@ -67,7 +65,7 @@ public class UnwindOperationUnitTests {
UnwindOperation unwindOperation = Aggregation.unwind("a");
assertThat(unwindOperation.getFields().exposesNoFields(), is(true));
assertThat(unwindOperation.getFields().exposesNoFields()).isTrue();
}
@Test // DATAMONGO-1391
@@ -77,10 +75,9 @@ public class UnwindOperationUnitTests {
Document unwindClause = extractDocumentFromUnwindOperation(unwindOperation);
assertThat(unwindClause,
isBsonObject().containing("path", "$a").//
containing("preserveNullAndEmptyArrays", true).//
notContaining("includeArrayIndex"));
assertThat(unwindClause).containsEntry("path", "$a").//
containsEntry("preserveNullAndEmptyArrays", true).//
doesNotContainKey("includeArrayIndex");
}
@Test // DATAMONGO-1391
@@ -89,7 +86,7 @@ public class UnwindOperationUnitTests {
UnwindOperation unwindOperation = UnwindOperation.newUnwind().path("$foo").noArrayIndex().skipNullAndEmptyArrays();
Document pipeline = unwindOperation.toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(pipeline, isBsonObject().containing("$unwind", "$foo"));
assertThat(pipeline).containsEntry("$unwind", "$foo");
}
@Test // DATAMONGO-1391
@@ -100,10 +97,9 @@ public class UnwindOperationUnitTests {
Document unwindClause = extractDocumentFromUnwindOperation(unwindOperation);
assertThat(unwindClause,
isBsonObject().containing("path", "$foo").//
containing("preserveNullAndEmptyArrays", true).//
containing("includeArrayIndex", "myindex"));
assertThat(unwindClause).containsEntry("path", "$foo").//
containsEntry("preserveNullAndEmptyArrays", true).//
containsEntry("includeArrayIndex", "myindex");
}
private Document extractDocumentFromUnwindOperation(UnwindOperation unwindOperation) {

View File

@@ -15,19 +15,19 @@
*/
package org.springframework.data.mongodb.core.convert;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.Arrays;
import java.util.HashSet;
import org.bson.Document;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.annotation.Id;
import org.springframework.data.convert.CustomConversions;
@@ -109,7 +109,7 @@ public class CustomConvertersUnitTests {
Document document = new Document();
document.put("foo", null);
Assert.assertThat(document.containsKey("foo"), CoreMatchers.is(true));
assertThat(document.containsKey("foo")).isEqualTo(true);
}
public static class Foo {

View File

@@ -15,7 +15,7 @@
*/
package org.springframework.data.mongodb.core.convert;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.ArrayList;
@@ -27,6 +27,7 @@ import org.bson.Document;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
/**
@@ -67,9 +68,9 @@ public class DataMongo273Tests {
@SuppressWarnings("unchecked")
Map<String, Object> mapOfThings2 = converter.read(Map.class, result);
assertTrue(mapOfThings2.get("plane") instanceof Plane);
assertTrue(mapOfThings2.get("train") instanceof Train);
assertTrue(mapOfThings2.get("automobile") instanceof Automobile);
assertThat(mapOfThings2.get("plane") instanceof Plane).isTrue();
assertThat(mapOfThings2.get("train") instanceof Train).isTrue();
assertThat(mapOfThings2.get("automobile") instanceof Automobile).isTrue();
}
@Test // DATAMONGO-294
@@ -90,9 +91,9 @@ public class DataMongo273Tests {
List listOfThings2 = converter.read(List.class, result);
assertTrue(listOfThings2.get(0) instanceof Plane);
assertTrue(listOfThings2.get(1) instanceof Train);
assertTrue(listOfThings2.get(2) instanceof Automobile);
assertThat(listOfThings2.get(0) instanceof Plane).isTrue();
assertThat(listOfThings2.get(1) instanceof Train).isTrue();
assertThat(listOfThings2.get(2) instanceof Automobile).isTrue();
}
@Test // DATAMONGO-294
@@ -120,9 +121,9 @@ public class DataMongo273Tests {
List listOfThings2 = (List) shipment2.getBoxes().get("one");
assertTrue(listOfThings2.get(0) instanceof Plane);
assertTrue(listOfThings2.get(1) instanceof Train);
assertTrue(listOfThings2.get(2) instanceof Automobile);
assertThat(listOfThings2.get(0) instanceof Plane).isTrue();
assertThat(listOfThings2.get(1) instanceof Train).isTrue();
assertThat(listOfThings2.get(2) instanceof Automobile).isTrue();
}
static class Plane {

View File

@@ -15,10 +15,8 @@
*/
package org.springframework.data.mongodb.core.convert;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.any;
import static org.springframework.data.mongodb.core.convert.LazyLoadingTestUtils.*;
import java.io.Serializable;
@@ -42,6 +40,7 @@ import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.annotation.AccessType;
import org.springframework.data.annotation.AccessType.Type;
import org.springframework.data.annotation.Id;
@@ -54,7 +53,6 @@ import org.springframework.data.mongodb.core.convert.MappingMongoConverterUnitTe
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.util.MongoClientVersion;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.SerializationUtils;
@@ -97,8 +95,8 @@ public class DbRefMappingMongoConverterUnitTests {
person.id = "foo";
DBRef dbRef = converter.toDBRef(person, null);
assertThat(dbRef.getId(), is("foo"));
assertThat(dbRef.getCollectionName(), is("person"));
assertThat(dbRef.getId()).isEqualTo("foo");
assertThat(dbRef.getCollectionName()).isEqualTo("person");
}
@Test // DATAMONGO-657
@@ -135,13 +133,13 @@ public class DbRefMappingMongoConverterUnitTests {
Document map = (Document) document.get("map");
assertThat(map.get("test"), instanceOf(DBRef.class));
assertThat(map.get("test")).isInstanceOf(DBRef.class);
((Document) document.get("map")).put("test", dbRef);
MapDBRef read = converter.read(MapDBRef.class, document);
assertThat(read.map.get("test").id, is(BigInteger.ONE));
assertThat(read.map.get("test").id).isEqualTo(BigInteger.ONE);
}
@Test // DATAMONGO-347
@@ -154,8 +152,8 @@ public class DbRefMappingMongoConverterUnitTests {
person.id = "foo";
DBRef dbRef = converter.toDBRef(person, property);
assertThat(dbRef.getId(), is("foo"));
assertThat(dbRef.getCollectionName(), is("person"));
assertThat(dbRef.getId()).isEqualTo("foo");
assertThat(dbRef.getCollectionName()).isEqualTo("person");
}
@Test // DATAMONGO-348
@@ -174,9 +172,9 @@ public class DbRefMappingMongoConverterUnitTests {
ClassWithLazyDbRefs result = converterSpy.read(ClassWithLazyDbRefs.class, document);
assertProxyIsResolved(result.dbRefToInterface, false);
assertThat(result.dbRefToInterface.get(0).getId(), is(id));
assertThat(result.dbRefToInterface.get(0).getId()).isEqualTo(id);
assertProxyIsResolved(result.dbRefToInterface, true);
assertThat(result.dbRefToInterface.get(0).getValue(), is(value));
assertThat(result.dbRefToInterface.get(0).getValue()).isEqualTo(value);
}
@Test // DATAMONGO-348
@@ -195,9 +193,9 @@ public class DbRefMappingMongoConverterUnitTests {
ClassWithLazyDbRefs result = converterSpy.read(ClassWithLazyDbRefs.class, document);
assertProxyIsResolved(result.dbRefToConcreteCollection, false);
assertThat(result.dbRefToConcreteCollection.get(0).getId(), is(id));
assertThat(result.dbRefToConcreteCollection.get(0).getId()).isEqualTo(id);
assertProxyIsResolved(result.dbRefToConcreteCollection, true);
assertThat(result.dbRefToConcreteCollection.get(0).getValue(), is(value));
assertThat(result.dbRefToConcreteCollection.get(0).getValue()).isEqualTo(value);
}
@Test // DATAMONGO-348
@@ -216,9 +214,9 @@ public class DbRefMappingMongoConverterUnitTests {
ClassWithLazyDbRefs result = converterSpy.read(ClassWithLazyDbRefs.class, document);
assertProxyIsResolved(result.dbRefToConcreteType, false);
assertThat(result.dbRefToConcreteType.getId(), is(id));
assertThat(result.dbRefToConcreteType.getId()).isEqualTo(id);
assertProxyIsResolved(result.dbRefToConcreteType, true);
assertThat(result.dbRefToConcreteType.getValue(), is(value));
assertThat(result.dbRefToConcreteType.getValue()).isEqualTo(value);
}
@Test // DATAMONGO-348
@@ -237,9 +235,9 @@ public class DbRefMappingMongoConverterUnitTests {
ClassWithLazyDbRefs result = converterSpy.read(ClassWithLazyDbRefs.class, document);
assertProxyIsResolved(result.dbRefToConcreteTypeWithPersistenceConstructor, false);
assertThat(result.dbRefToConcreteTypeWithPersistenceConstructor.getId(), is(id));
assertThat(result.dbRefToConcreteTypeWithPersistenceConstructor.getId()).isEqualTo(id);
assertProxyIsResolved(result.dbRefToConcreteTypeWithPersistenceConstructor, true);
assertThat(result.dbRefToConcreteTypeWithPersistenceConstructor.getValue(), is(value));
assertThat(result.dbRefToConcreteTypeWithPersistenceConstructor.getValue()).isEqualTo(value);
}
@Test // DATAMONGO-348
@@ -259,9 +257,10 @@ public class DbRefMappingMongoConverterUnitTests {
ClassWithLazyDbRefs result = converterSpy.read(ClassWithLazyDbRefs.class, document);
assertProxyIsResolved(result.dbRefToConcreteTypeWithPersistenceConstructorWithoutDefaultConstructor, false);
assertThat(result.dbRefToConcreteTypeWithPersistenceConstructorWithoutDefaultConstructor.getId(), is(id));
assertThat(result.dbRefToConcreteTypeWithPersistenceConstructorWithoutDefaultConstructor.getId()).isEqualTo(id);
assertProxyIsResolved(result.dbRefToConcreteTypeWithPersistenceConstructorWithoutDefaultConstructor, true);
assertThat(result.dbRefToConcreteTypeWithPersistenceConstructorWithoutDefaultConstructor.getValue(), is(value));
assertThat(result.dbRefToConcreteTypeWithPersistenceConstructorWithoutDefaultConstructor.getValue())
.isEqualTo(value);
}
@Test // DATAMONGO-348
@@ -281,9 +280,9 @@ public class DbRefMappingMongoConverterUnitTests {
SerializableClassWithLazyDbRefs deserializedResult = (SerializableClassWithLazyDbRefs) transport(result);
assertThat(deserializedResult.dbRefToSerializableTarget.getId(), is(id));
assertThat(deserializedResult.dbRefToSerializableTarget.getId()).isEqualTo(id);
assertProxyIsResolved(deserializedResult.dbRefToSerializableTarget, true);
assertThat(deserializedResult.dbRefToSerializableTarget.getValue(), is(value));
assertThat(deserializedResult.dbRefToSerializableTarget.getValue()).isEqualTo(value);
}
@Test // DATAMONGO-884
@@ -301,9 +300,9 @@ public class DbRefMappingMongoConverterUnitTests {
WithObjectMethodOverrideLazyDbRefs result = converterSpy.read(WithObjectMethodOverrideLazyDbRefs.class, document);
assertThat(result.dbRefToToStringObjectMethodOverride, is(notNullValue()));
assertThat(result.dbRefToToStringObjectMethodOverride).isNotNull();
assertProxyIsResolved(result.dbRefToToStringObjectMethodOverride, false);
assertThat(result.dbRefToToStringObjectMethodOverride.toString(), is(id + ":" + value));
assertThat(result.dbRefToToStringObjectMethodOverride.toString()).isEqualTo(id + ":" + value);
assertProxyIsResolved(result.dbRefToToStringObjectMethodOverride, true);
}
@@ -322,16 +321,16 @@ public class DbRefMappingMongoConverterUnitTests {
WithObjectMethodOverrideLazyDbRefs result = converterSpy.read(WithObjectMethodOverrideLazyDbRefs.class, document);
assertThat(result.dbRefToPlainObject, is(notNullValue()));
assertThat(result.dbRefToPlainObject).isNotNull();
assertProxyIsResolved(result.dbRefToPlainObject, false);
// calling Object#toString does not initialize the proxy.
String proxyString = result.dbRefToPlainObject.toString();
assertThat(proxyString, is("lazyDbRefTarget" + ":" + id + "$LazyLoadingProxy"));
assertThat(proxyString).isEqualTo("lazyDbRefTarget" + ":" + id + "$LazyLoadingProxy");
assertProxyIsResolved(result.dbRefToPlainObject, false);
// calling another method not declared on object triggers proxy initialization.
assertThat(result.dbRefToPlainObject.getValue(), is(value));
assertThat(result.dbRefToPlainObject.getValue()).isEqualTo(value);
assertProxyIsResolved(result.dbRefToPlainObject, true);
}
@@ -350,12 +349,12 @@ public class DbRefMappingMongoConverterUnitTests {
WithObjectMethodOverrideLazyDbRefs result = converterSpy.read(WithObjectMethodOverrideLazyDbRefs.class, document);
assertThat(result.dbRefToPlainObject, is(notNullValue()));
assertThat(result.dbRefToPlainObject).isNotNull();
assertProxyIsResolved(result.dbRefToPlainObject, false);
assertThat(result.dbRefToPlainObject, is(equalTo(result.dbRefToPlainObject)));
assertThat(result.dbRefToPlainObject, is(not(equalTo(null))));
assertThat(result.dbRefToPlainObject, is(not(equalTo((Object) lazyDbRefs.dbRefToToStringObjectMethodOverride))));
assertThat(result.dbRefToPlainObject).isEqualTo(result.dbRefToPlainObject);
assertThat(result.dbRefToPlainObject).isNotEqualTo(null);
assertThat(result.dbRefToPlainObject).isNotEqualTo((Object) lazyDbRefs.dbRefToToStringObjectMethodOverride);
assertProxyIsResolved(result.dbRefToPlainObject, false);
}
@@ -375,10 +374,10 @@ public class DbRefMappingMongoConverterUnitTests {
WithObjectMethodOverrideLazyDbRefs result = converterSpy.read(WithObjectMethodOverrideLazyDbRefs.class, document);
assertThat(result.dbRefToPlainObject, is(notNullValue()));
assertThat(result.dbRefToPlainObject).isNotNull();
assertProxyIsResolved(result.dbRefToPlainObject, false);
assertThat(result.dbRefToPlainObject.hashCode(), is(311365444));
assertThat(result.dbRefToPlainObject.hashCode()).isEqualTo(311365444);
assertProxyIsResolved(result.dbRefToPlainObject, false);
}
@@ -402,12 +401,12 @@ public class DbRefMappingMongoConverterUnitTests {
WithObjectMethodOverrideLazyDbRefs result = converterSpy.read(WithObjectMethodOverrideLazyDbRefs.class, document);
assertProxyIsResolved(result.dbRefEqualsAndHashcodeObjectMethodOverride1, false);
assertThat(result.dbRefEqualsAndHashcodeObjectMethodOverride1, is(notNullValue()));
assertThat(result.dbRefEqualsAndHashcodeObjectMethodOverride1).isNotNull();
result.dbRefEqualsAndHashcodeObjectMethodOverride1.equals(null);
assertProxyIsResolved(result.dbRefEqualsAndHashcodeObjectMethodOverride1, true);
assertProxyIsResolved(result.dbRefEqualsAndHashcodeObjectMethodOverride2, false);
assertThat(result.dbRefEqualsAndHashcodeObjectMethodOverride2, is(notNullValue()));
assertThat(result.dbRefEqualsAndHashcodeObjectMethodOverride2).isNotNull();
result.dbRefEqualsAndHashcodeObjectMethodOverride2.hashCode();
assertProxyIsResolved(result.dbRefEqualsAndHashcodeObjectMethodOverride2, true);
}
@@ -422,12 +421,12 @@ public class DbRefMappingMongoConverterUnitTests {
ClassWithLazyDbRefs result = converter.read(ClassWithLazyDbRefs.class, document);
assertThat(result.id, is(lazyDbRefs.id));
assertThat(result.dbRefToInterface, is(nullValue()));
assertThat(result.dbRefToConcreteCollection, is(nullValue()));
assertThat(result.dbRefToConcreteType, is(nullValue()));
assertThat(result.dbRefToConcreteTypeWithPersistenceConstructor, is(nullValue()));
assertThat(result.dbRefToConcreteTypeWithPersistenceConstructorWithoutDefaultConstructor, is(nullValue()));
assertThat(result.id).isEqualTo(lazyDbRefs.id);
assertThat(result.dbRefToInterface).isNull();
assertThat(result.dbRefToConcreteCollection).isNull();
assertThat(result.dbRefToConcreteType).isNull();
assertThat(result.dbRefToConcreteTypeWithPersistenceConstructor).isNull();
assertThat(result.dbRefToConcreteTypeWithPersistenceConstructorWithoutDefaultConstructor).isNull();
}
@Test // DATAMONGO-1005
@@ -442,8 +441,8 @@ public class DbRefMappingMongoConverterUnitTests {
ClassWithDbRefField found = converter.read(ClassWithDbRefField.class, document);
assertThat(found, is(notNullValue()));
assertThat(found.reference, is(found));
assertThat(found).isNotNull();
assertThat(found.reference).isEqualTo(found);
}
@Test // DATAMONGO-1005
@@ -460,9 +459,9 @@ public class DbRefMappingMongoConverterUnitTests {
ClassWithNestedDbRefField found = converter.read(ClassWithNestedDbRefField.class, document);
assertThat(found, is(notNullValue()));
assertThat(found.nested, is(notNullValue()));
assertThat(found.nested.reference, is(found));
assertThat(found).isNotNull();
assertThat(found.nested).isNotNull();
assertThat(found.nested.reference).isEqualTo(found);
}
@Test // DATAMONGO-1012
@@ -483,7 +482,7 @@ public class DbRefMappingMongoConverterUnitTests {
MongoPersistentProperty idProperty = mappingContext.getRequiredPersistentEntity(LazyDbRefTarget.class)
.getIdProperty();
assertThat(accessor.getProperty(idProperty), is(notNullValue()));
assertThat(accessor.getProperty(idProperty)).isNotNull();
assertProxyIsResolved(result.dbRefToConcreteType, false);
}
@@ -501,7 +500,7 @@ public class DbRefMappingMongoConverterUnitTests {
ClassWithLazyDbRefs result = converter.read(ClassWithLazyDbRefs.class, object);
LazyDbRefTargetPropertyAccess proxy = result.dbRefToConcreteTypeWithPropertyAccess;
assertThat(ReflectionTestUtils.getField(proxy, "id"), is(nullValue()));
assertThat(ReflectionTestUtils.getField(proxy, "id")).isNull();
assertProxyIsResolved(proxy, false);
}
@@ -544,9 +543,9 @@ public class DbRefMappingMongoConverterUnitTests {
ClassWithLazyDbRefs result = converterSpy.read(ClassWithLazyDbRefs.class, document);
assertProxyIsResolved(result.dbRefToConcreteCollection, false);
assertThat(result.dbRefToConcreteCollection.get(0).getId(), is(id1));
assertThat(result.dbRefToConcreteCollection.get(0).getId()).isEqualTo(id1);
assertProxyIsResolved(result.dbRefToConcreteCollection, true);
assertThat(result.dbRefToConcreteCollection.get(1).getId(), is(id2));
assertThat(result.dbRefToConcreteCollection.get(1).getId()).isEqualTo(id2);
verify(converterSpy, never()).readRef(Mockito.any(DBRef.class));
}
@@ -568,7 +567,7 @@ public class DbRefMappingMongoConverterUnitTests {
ClassWithDbRefSetConstructor result = converterSpy.read(ClassWithDbRefSetConstructor.class, document);
assertThat(result.dbRefToInterface, is(instanceOf(Set.class)));
assertThat(result.dbRefToInterface).isInstanceOf(Set.class);
verify(converterSpy, never()).readRef(Mockito.any(DBRef.class));
}
@@ -593,9 +592,9 @@ public class DbRefMappingMongoConverterUnitTests {
ClassWithLazyDbRefs result = converterSpy.read(ClassWithLazyDbRefs.class, document);
assertProxyIsResolved(result.dbRefToConcreteCollection, false);
assertThat(result.dbRefToConcreteCollection.get(0).getId(), is(id1));
assertThat(result.dbRefToConcreteCollection.get(0).getId()).isEqualTo(id1);
assertProxyIsResolved(result.dbRefToConcreteCollection, true);
assertThat(result.dbRefToConcreteCollection.get(1).getId(), is(id2));
assertThat(result.dbRefToConcreteCollection.get(1).getId()).isEqualTo(id2);
verify(converterSpy, times(2)).readRef(Mockito.any(DBRef.class));
verify(converterSpy, never()).bulkReadRefs(anyList());
@@ -625,9 +624,9 @@ public class DbRefMappingMongoConverterUnitTests {
MapDBRef result = converterSpy.read(MapDBRef.class, document);
// assertProxyIsResolved(result.map, false);
assertThat(result.map.get("one").id, is(val1.id));
assertThat(result.map.get("one").id).isEqualTo(val1.id);
// assertProxyIsResolved(result.map, true);
assertThat(result.map.get("two").id, is(val2.id));
assertThat(result.map.get("two").id).isEqualTo(val2.id);
verify(converterSpy, times(1)).bulkReadRefs(anyList());
verify(converterSpy, never()).readRef(Mockito.any(DBRef.class));
@@ -657,9 +656,9 @@ public class DbRefMappingMongoConverterUnitTests {
MapDBRef result = converterSpy.read(MapDBRef.class, document);
assertProxyIsResolved(result.lazyMap, false);
assertThat(result.lazyMap.get("one").id, is(val1.id));
assertThat(result.lazyMap.get("one").id).isEqualTo(val1.id);
assertProxyIsResolved(result.lazyMap, true);
assertThat(result.lazyMap.get("two").id, is(val2.id));
assertThat(result.lazyMap.get("two").id).isEqualTo(val2.id);
verify(converterSpy, times(1)).bulkReadRefs(anyList());
verify(converterSpy, never()).readRef(any());

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core.convert;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Arrays;
import java.util.Collections;
@@ -25,6 +24,7 @@ import java.util.List;
import org.bson.Document;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.convert.ConfigurableTypeInformationMapper;
import org.springframework.data.convert.SimpleTypeInformationMapper;
import org.springframework.data.mongodb.core.DocumentTestUtils;
@@ -115,8 +115,8 @@ public class DefaultMongoTypeMapperUnitTests {
Document typeInfo = DocumentTestUtils.getAsDocument(result, DefaultMongoTypeMapper.DEFAULT_TYPE_KEY);
List<Object> aliases = DocumentTestUtils.getAsDBList(typeInfo, "$in");
assertThat(aliases, hasSize(1));
assertThat(aliases.get(0), is((Object) String.class.getName()));
assertThat(aliases).hasSize(1);
assertThat(aliases.get(0)).isEqualTo((Object) String.class.getName());
}
@Test
@@ -173,15 +173,15 @@ public class DefaultMongoTypeMapperUnitTests {
@Test
public void returnsCorrectTypeKey() {
assertThat(typeMapper.isTypeKey(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY), is(true));
assertThat(typeMapper.isTypeKey(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY)).isTrue();
typeMapper = new DefaultMongoTypeMapper("_custom");
assertThat(typeMapper.isTypeKey("_custom"), is(true));
assertThat(typeMapper.isTypeKey(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY), is(false));
assertThat(typeMapper.isTypeKey("_custom")).isTrue();
assertThat(typeMapper.isTypeKey(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY)).isFalse();
typeMapper = new DefaultMongoTypeMapper(null);
assertThat(typeMapper.isTypeKey("_custom"), is(false));
assertThat(typeMapper.isTypeKey(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY), is(false));
assertThat(typeMapper.isTypeKey("_custom")).isFalse();
assertThat(typeMapper.isTypeKey(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY)).isFalse();
}
private void readsTypeFromField(Document document, Class<?> type) {
@@ -189,10 +189,10 @@ public class DefaultMongoTypeMapperUnitTests {
TypeInformation<?> typeInfo = typeMapper.readType(document);
if (type != null) {
assertThat(typeInfo, is(notNullValue()));
assertThat(typeInfo.getType(), is(typeCompatibleWith(type)));
assertThat(typeInfo).isNotNull();
assertThat(typeInfo.getType()).isAssignableFrom(type);
} else {
assertThat(typeInfo, is(nullValue()));
assertThat(typeInfo).isNull();
}
}
@@ -201,10 +201,10 @@ public class DefaultMongoTypeMapperUnitTests {
typeMapper.writeType(type, document);
if (field == null) {
assertThat(document.keySet().isEmpty(), is(true));
assertThat(document.keySet().isEmpty()).isTrue();
} else {
assertThat(document.containsKey(field), is(true));
assertThat(document.get(field), is((Object) type.getName()));
assertThat(document.containsKey(field)).isTrue();
assertThat(document.get(field)).isEqualTo((Object) type.getName());
}
}
@@ -213,10 +213,10 @@ public class DefaultMongoTypeMapperUnitTests {
typeMapper.writeType(type, document);
if (value == null) {
assertThat(document.keySet().isEmpty(), is(true));
assertThat(document.keySet().isEmpty()).isTrue();
} else {
assertThat(document.containsKey(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY), is(true));
assertThat(document.get(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY), is(value));
assertThat(document.containsKey(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY)).isTrue();
assertThat(document.get(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY)).isEqualTo(value);
}
}
}

View File

@@ -15,12 +15,12 @@
*/
package org.springframework.data.mongodb.core.convert;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.bson.BsonDocument;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.mongodb.core.DocumentTestUtils;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
@@ -49,7 +49,7 @@ public class DocumentAccessorUnitTests {
accessor.put(fooProperty, "FooBar");
Document aDocument = DocumentTestUtils.getAsDocument(document, "a");
assertThat(aDocument.get("b"), is((Object) "FooBar"));
assertThat(aDocument.get("b")).isEqualTo((Object) "FooBar");
}
@Test // DATAMONGO-766
@@ -58,14 +58,14 @@ public class DocumentAccessorUnitTests {
Document source = new Document("a", new Document("b", "FooBar"));
DocumentAccessor accessor = new DocumentAccessor(source);
assertThat(accessor.get(fooProperty), is((Object) "FooBar"));
assertThat(accessor.get(fooProperty)).isEqualTo((Object) "FooBar");
}
@Test // DATAMONGO-766
public void returnsNullForNonExistingFieldPath() {
DocumentAccessor accessor = new DocumentAccessor(new Document());
assertThat(accessor.get(fooProperty), is(nullValue()));
assertThat(accessor.get(fooProperty)).isNull();
}
@Test(expected = IllegalArgumentException.class) // DATAMONGO-766
@@ -92,9 +92,9 @@ public class DocumentAccessorUnitTests {
Document nestedA = DocumentTestUtils.getAsDocument(target, "a");
assertThat(nestedA, is(notNullValue()));
assertThat(nestedA.get("b"), is((Object) "b"));
assertThat(nestedA.get("c"), is((Object) "c"));
assertThat(nestedA).isNotNull();
assertThat(nestedA.get("b")).isEqualTo((Object) "b");
assertThat(nestedA.get("c")).isEqualTo((Object) "c");
}
@Test // DATAMONGO-1471
@@ -103,9 +103,9 @@ public class DocumentAccessorUnitTests {
DocumentAccessor accessor = new DocumentAccessor(new Document("a", new BasicDBObject("c", "d")));
MongoPersistentEntity<?> entity = context.getRequiredPersistentEntity(ProjectingType.class);
assertThat(accessor.hasValue(entity.getRequiredPersistentProperty("foo")), is(false));
assertThat(accessor.hasValue(entity.getRequiredPersistentProperty("a")), is(true));
assertThat(accessor.hasValue(entity.getRequiredPersistentProperty("name")), is(false));
assertThat(accessor.hasValue(entity.getRequiredPersistentProperty("foo"))).isFalse();
assertThat(accessor.hasValue(entity.getRequiredPersistentProperty("a"))).isTrue();
assertThat(accessor.hasValue(entity.getRequiredPersistentProperty("name"))).isFalse();
}
static class ProjectingType {

View File

@@ -15,31 +15,21 @@
*/
package org.springframework.data.mongodb.core.convert;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Arrays;
import java.util.List;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.geo.Box;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.geo.Point;
import org.springframework.data.geo.Polygon;
import org.springframework.data.mongodb.core.convert.GeoConverters.BoxToDocumentConverter;
import org.springframework.data.mongodb.core.convert.GeoConverters.CircleToDocumentConverter;
import org.springframework.data.mongodb.core.convert.GeoConverters.DocumentToBoxConverter;
import org.springframework.data.mongodb.core.convert.GeoConverters.DocumentToCircleConverter;
import org.springframework.data.mongodb.core.convert.GeoConverters.DocumentToPointConverter;
import org.springframework.data.mongodb.core.convert.GeoConverters.DocumentToPolygonConverter;
import org.springframework.data.mongodb.core.convert.GeoConverters.DocumentToSphereConverter;
import org.springframework.data.mongodb.core.convert.GeoConverters.GeoCommandToDocumentConverter;
import org.springframework.data.mongodb.core.convert.GeoConverters.PointToDocumentConverter;
import org.springframework.data.mongodb.core.convert.GeoConverters.PolygonToDocumentConverter;
import org.springframework.data.mongodb.core.convert.GeoConverters.SphereToDocumentConverter;
import org.springframework.data.mongodb.core.convert.GeoConverters.*;
import org.springframework.data.mongodb.core.geo.Sphere;
import org.springframework.data.mongodb.core.query.GeoCommand;
@@ -61,8 +51,8 @@ public class GeoConvertersUnitTests {
Document document = BoxToDocumentConverter.INSTANCE.convert(box);
Box result = DocumentToBoxConverter.INSTANCE.convert(document);
assertThat(result, is(box));
assertThat(result.getClass().equals(Box.class), is(true));
assertThat(result).isEqualTo(box);
assertThat(result.getClass().equals(Box.class)).isTrue();
}
@Test // DATAMONGO-858
@@ -73,7 +63,7 @@ public class GeoConvertersUnitTests {
Document document = CircleToDocumentConverter.INSTANCE.convert(circle);
Circle result = DocumentToCircleConverter.INSTANCE.convert(document);
assertThat(result, is(circle));
assertThat(result).isEqualTo(circle);
}
@Test // DATAMONGO-858
@@ -85,8 +75,8 @@ public class GeoConvertersUnitTests {
Document document = CircleToDocumentConverter.INSTANCE.convert(circle);
Circle result = DocumentToCircleConverter.INSTANCE.convert(document);
assertThat(result, is(circle));
assertThat(result.getRadius(), is(radius));
assertThat(result).isEqualTo(circle);
assertThat(result.getRadius()).isEqualTo(radius);
}
@Test // DATAMONGO-858
@@ -97,8 +87,8 @@ public class GeoConvertersUnitTests {
Document document = PolygonToDocumentConverter.INSTANCE.convert(polygon);
Polygon result = DocumentToPolygonConverter.INSTANCE.convert(document);
assertThat(result, is(polygon));
assertThat(result.getClass().equals(Polygon.class), is(true));
assertThat(result).isEqualTo(polygon);
assertThat(result.getClass().equals(Polygon.class)).isTrue();
}
@Test // DATAMONGO-858
@@ -109,8 +99,8 @@ public class GeoConvertersUnitTests {
Document document = SphereToDocumentConverter.INSTANCE.convert(sphere);
Sphere result = DocumentToSphereConverter.INSTANCE.convert(document);
assertThat(result, is(sphere));
assertThat(result.getClass().equals(Sphere.class), is(true));
assertThat(result).isEqualTo(sphere);
assertThat(result.getClass().equals(Sphere.class)).isTrue();
}
@Test // DATAMONGO-858
@@ -122,9 +112,9 @@ public class GeoConvertersUnitTests {
Document document = SphereToDocumentConverter.INSTANCE.convert(sphere);
Sphere result = DocumentToSphereConverter.INSTANCE.convert(document);
assertThat(result, is(sphere));
assertThat(result.getRadius(), is(radius));
assertThat(result.getClass().equals(org.springframework.data.mongodb.core.geo.Sphere.class), is(true));
assertThat(result).isEqualTo(sphere);
assertThat(result.getRadius()).isEqualTo(radius);
assertThat(result.getClass().equals(Sphere.class)).isTrue();
}
@Test // DATAMONGO-858
@@ -135,8 +125,8 @@ public class GeoConvertersUnitTests {
Document document = PointToDocumentConverter.INSTANCE.convert(point);
Point result = DocumentToPointConverter.INSTANCE.convert(document);
assertThat(result, is(point));
assertThat(result.getClass().equals(Point.class), is(true));
assertThat(result).isEqualTo(point);
assertThat(result.getClass().equals(Point.class)).isTrue();
}
@Test // DATAMONGO-858
@@ -147,19 +137,19 @@ public class GeoConvertersUnitTests {
Document document = GeoCommandToDocumentConverter.INSTANCE.convert(cmd);
assertThat(document, is(notNullValue()));
assertThat(document).isNotNull();
List<Object> boxObject = (List<Object>) document.get("$box");
assertThat(boxObject,
is((Object) Arrays.asList(GeoConverters.toList(box.getFirst()), GeoConverters.toList(box.getSecond()))));
assertThat(boxObject)
.isEqualTo((Object) Arrays.asList(GeoConverters.toList(box.getFirst()), GeoConverters.toList(box.getSecond())));
}
@Test // DATAMONGO-1607
public void convertsPointCorrectlyWhenUsingNonDoubleForCoordinates() {
assertThat(DocumentToPointConverter.INSTANCE.convert(new Document().append("x", 1L).append("y", 2L)),
is(new Point(1, 2)));
assertThat(DocumentToPointConverter.INSTANCE.convert(new Document().append("x", 1L).append("y", 2L)))
.isEqualTo(new Point(1, 2));
}
@Test // DATAMONGO-1607
@@ -169,7 +159,8 @@ public class GeoConvertersUnitTests {
circle.put("center", new Document().append("x", 1).append("y", 2));
circle.put("radius", 3L);
assertThat(DocumentToCircleConverter.INSTANCE.convert(circle), is(new Circle(new Point(1, 2), new Distance(3))));
assertThat(DocumentToCircleConverter.INSTANCE.convert(circle))
.isEqualTo(new Circle(new Point(1, 2), new Distance(3)));
}
@Test // DATAMONGO-1607
@@ -179,7 +170,8 @@ public class GeoConvertersUnitTests {
sphere.put("center", new Document().append("x", 1).append("y", 2));
sphere.put("radius", 3L);
assertThat(DocumentToSphereConverter.INSTANCE.convert(sphere), is(new Sphere(new Point(1, 2), new Distance(3))));
assertThat(DocumentToSphereConverter.INSTANCE.convert(sphere))
.isEqualTo(new Sphere(new Point(1, 2), new Distance(3)));
}
}

View File

@@ -15,9 +15,7 @@
*/
package org.springframework.data.mongodb.core.convert;
import static org.hamcrest.core.IsEqual.*;
import static org.hamcrest.core.IsNull.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.test.util.Assertions.*;
import java.util.Arrays;
@@ -28,6 +26,7 @@ import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.convert.GeoConverters.DocumentToGeoJsonLineStringConverter;
import org.springframework.data.mongodb.core.convert.GeoConverters.DocumentToGeoJsonMultiLineStringConverter;
@@ -181,12 +180,12 @@ public class GeoJsonConverterUnitTests {
@Test // DATAMONGO-1137
public void shouldConvertDboCorrectly() {
assertThat(converter.convert(POLYGON_DOC), equalTo(POLYGON));
assertThat(converter.convert(POLYGON_DOC)).isEqualTo(POLYGON);
}
@Test // DATAMONGO-1137
public void shouldReturnNullWhenConvertIsGivenNull() {
assertThat(converter.convert(null), nullValue());
assertThat(converter.convert(null)).isNull();
}
@Test // DATAMONGO-1137
@@ -200,7 +199,7 @@ public class GeoJsonConverterUnitTests {
@Test // DATAMONGO-1399
public void shouldConvertDboWithMultipleRingsCorrectly() {
assertThat(converter.convert(POLYGON_WITH_2_RINGS_DOC), equalTo(POLYGON_WITH_2_RINGS));
assertThat(converter.convert(POLYGON_WITH_2_RINGS_DOC)).isEqualTo(POLYGON_WITH_2_RINGS);
}
}
@@ -215,12 +214,12 @@ public class GeoJsonConverterUnitTests {
@Test // DATAMONGO-1137
public void shouldConvertDboCorrectly() {
assertThat(converter.convert(SINGLE_POINT_DOC), equalTo(SINGLE_POINT));
assertThat(converter.convert(SINGLE_POINT_DOC)).isEqualTo(SINGLE_POINT);
}
@Test // DATAMONGO-1137
public void shouldReturnNullWhenConvertIsGivenNull() {
assertThat(converter.convert(null), nullValue());
assertThat(converter.convert(null)).isNull();
}
@Test // DATAMONGO-1137
@@ -243,12 +242,12 @@ public class GeoJsonConverterUnitTests {
@Test // DATAMONGO-1137
public void shouldConvertDboCorrectly() {
assertThat(converter.convert(LINE_STRING_DOC), equalTo(LINE_STRING));
assertThat(converter.convert(LINE_STRING_DOC)).isEqualTo(LINE_STRING);
}
@Test // DATAMONGO-1137
public void shouldReturnNullWhenConvertIsGivenNull() {
assertThat(converter.convert(null), nullValue());
assertThat(converter.convert(null)).isNull();
}
@Test // DATAMONGO-1137
@@ -271,12 +270,12 @@ public class GeoJsonConverterUnitTests {
@Test // DATAMONGO-1137
public void shouldConvertDboCorrectly() {
assertThat(converter.convert(MULTI_LINE_STRING_DOC), equalTo(MULTI_LINE_STRING));
assertThat(converter.convert(MULTI_LINE_STRING_DOC)).isEqualTo(MULTI_LINE_STRING);
}
@Test // DATAMONGO-1137
public void shouldReturnNullWhenConvertIsGivenNull() {
assertThat(converter.convert(null), nullValue());
assertThat(converter.convert(null)).isNull();
}
@Test // DATAMONGO-1137
@@ -299,12 +298,12 @@ public class GeoJsonConverterUnitTests {
@Test // DATAMONGO-1137
public void shouldConvertDboCorrectly() {
assertThat(converter.convert(MULTI_POINT_DOC), equalTo(MULTI_POINT));
assertThat(converter.convert(MULTI_POINT_DOC)).isEqualTo(MULTI_POINT);
}
@Test // DATAMONGO-1137
public void shouldReturnNullWhenConvertIsGivenNull() {
assertThat(converter.convert(null), nullValue());
assertThat(converter.convert(null)).isNull();
}
@Test // DATAMONGO-1137
@@ -327,12 +326,12 @@ public class GeoJsonConverterUnitTests {
@Test // DATAMONGO-1137
public void shouldConvertDboCorrectly() {
assertThat(converter.convert(MULTI_POLYGON_DOC), equalTo(MULTI_POLYGON));
assertThat(converter.convert(MULTI_POLYGON_DOC)).isEqualTo(MULTI_POLYGON);
}
@Test // DATAMONGO-1137
public void shouldReturnNullWhenConvertIsGivenNull() {
assertThat(converter.convert(null), nullValue());
assertThat(converter.convert(null)).isNull();
}
@Test // DATAMONGO-1137
@@ -354,47 +353,47 @@ public class GeoJsonConverterUnitTests {
// DATAMONGO-1135
public void convertShouldReturnNullWhenGivenNull() {
assertThat(converter.convert(null), nullValue());
assertThat(converter.convert(null)).isNull();
}
@Test // DATAMONGO-1135
public void shouldConvertGeoJsonPointCorrectly() {
assertThat(converter.convert(SINGLE_POINT), equalTo(SINGLE_POINT_DOC));
assertThat(converter.convert(SINGLE_POINT)).isEqualTo(SINGLE_POINT_DOC);
}
@Test // DATAMONGO-1135
public void shouldConvertGeoJsonPolygonCorrectly() {
assertThat(converter.convert(POLYGON), equalTo(POLYGON_DOC));
assertThat(converter.convert(POLYGON)).isEqualTo(POLYGON_DOC);
}
@Test // DATAMONGO-1137
public void shouldConvertGeoJsonLineStringCorrectly() {
assertThat(converter.convert(LINE_STRING), equalTo(LINE_STRING_DOC));
assertThat(converter.convert(LINE_STRING)).isEqualTo(LINE_STRING_DOC);
}
@Test // DATAMONGO-1137
public void shouldConvertGeoJsonMultiLineStringCorrectly() {
assertThat(converter.convert(MULTI_LINE_STRING), equalTo(MULTI_LINE_STRING_DOC));
assertThat(converter.convert(MULTI_LINE_STRING)).isEqualTo(MULTI_LINE_STRING_DOC);
}
@Test // DATAMONGO-1137
public void shouldConvertGeoJsonMultiPointCorrectly() {
assertThat(converter.convert(MULTI_POINT), equalTo(MULTI_POINT_DOC));
assertThat(converter.convert(MULTI_POINT)).isEqualTo(MULTI_POINT_DOC);
}
@Test // DATAMONGO-1137
public void shouldConvertGeoJsonMultiPolygonCorrectly() {
assertThat(converter.convert(MULTI_POLYGON), equalTo(MULTI_POLYGON_DOC));
assertThat(converter.convert(MULTI_POLYGON)).isEqualTo(MULTI_POLYGON_DOC);
}
@Test // DATAMONGO-1137
public void shouldConvertGeometryCollectionCorrectly() {
assertThat(converter.convert(GEOMETRY_COLLECTION), equalTo(GEOMETRY_COLLECTION_DOC));
assertThat(converter.convert(GEOMETRY_COLLECTION)).isEqualTo(GEOMETRY_COLLECTION_DOC);
}
@Test // DATAMONGO-1399
public void shouldConvertGeoJsonPolygonWithMultipleRingsCorrectly() {
assertThat(converter.convert(POLYGON_WITH_2_RINGS), equalTo(POLYGON_WITH_2_RINGS_DOC));
assertThat(converter.convert(POLYGON_WITH_2_RINGS)).isEqualTo(POLYGON_WITH_2_RINGS_DOC);
}
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core.convert;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.springframework.aop.framework.Advised;
import org.springframework.cglib.proxy.Factory;
@@ -40,8 +39,14 @@ public class LazyLoadingTestUtils {
public static void assertProxyIsResolved(Object target, boolean expected) {
LazyLoadingInterceptor interceptor = extractInterceptor(target);
assertThat(ReflectionTestUtils.getField(interceptor, "resolved"), is((Object) expected));
assertThat(ReflectionTestUtils.getField(interceptor, "result"), is(expected ? notNullValue() : nullValue()));
assertThat(ReflectionTestUtils.getField(interceptor, "resolved")).isEqualTo((Object) expected);
if (expected) {
assertThat(ReflectionTestUtils.getField(interceptor, "result")).isNotNull();
} else {
assertThat(ReflectionTestUtils.getField(interceptor, "result")).isNull();
}
}
private static LazyLoadingInterceptor extractInterceptor(Object proxy) {

View File

@@ -15,25 +15,24 @@
*/
package org.springframework.data.mongodb.core.convert;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.springframework.data.domain.Example.*;
import static org.springframework.data.domain.ExampleMatcher.*;
import static org.springframework.data.mongodb.core.DocumentTestUtils.*;
import static org.springframework.data.mongodb.test.util.IsBsonObject.*;
import static org.springframework.data.mongodb.test.util.Assertions.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import org.bson.conversions.Bson;
import org.hamcrest.core.Is;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.annotation.Id;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
@@ -47,7 +46,6 @@ import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.core.query.UntypedExampleMatcher;
import org.springframework.data.mongodb.test.util.IsBsonObject;
import org.springframework.data.util.TypeInformation;
/**
@@ -80,10 +78,8 @@ public class MongoExampleMapperUnitTests {
FlatDocument probe = new FlatDocument();
probe.id = "steelheart";
IsBsonObject<Bson> expected = isBsonObject().containing("_id", "steelheart");
assertThat(mapper.getMappedExample(of(probe), context.getRequiredPersistentEntity(FlatDocument.class)),
is(expected));
assertThat(mapper.getMappedExample(of(probe), context.getRequiredPersistentEntity(FlatDocument.class)))
.containsEntry("_id", "steelheart");
}
@Test // DATAMONGO-1245
@@ -94,13 +90,10 @@ public class MongoExampleMapperUnitTests {
probe.stringValue = "firefight";
probe.intValue = 100;
IsBsonObject<Bson> expected = isBsonObject().//
containing("_id", "steelheart").//
containing("stringValue", "firefight").//
containing("intValue", 100);
assertThat(mapper.getMappedExample(of(probe), context.getRequiredPersistentEntity(FlatDocument.class)),
is(expected));
assertThat(mapper.getMappedExample(of(probe), context.getRequiredPersistentEntity(FlatDocument.class)))
.containsEntry("_id", "steelheart") //
.containsEntry("stringValue", "firefight") //
.containsEntry("intValue", 100);
}
@Test // DATAMONGO-1245
@@ -110,12 +103,9 @@ public class MongoExampleMapperUnitTests {
probe.stringValue = "firefight";
probe.intValue = 100;
IsBsonObject<Bson> expected = isBsonObject().//
containing("stringValue", "firefight").//
containing("intValue", 100);
assertThat(mapper.getMappedExample(of(probe), context.getRequiredPersistentEntity(FlatDocument.class)),
is(expected));
assertThat(mapper.getMappedExample(of(probe), context.getRequiredPersistentEntity(FlatDocument.class))) //
.containsEntry("stringValue", "firefight") //
.containsEntry("intValue", 100);
}
@Test // DATAMONGO-1245
@@ -126,11 +116,8 @@ public class MongoExampleMapperUnitTests {
List list = (Arrays.asList("Prof", "Tia", "David"));
IsBsonObject<Bson> expected = isBsonObject().//
containing("listOfString", list);
assertThat(mapper.getMappedExample(of(probe), context.getRequiredPersistentEntity(FlatDocument.class)),
is(expected));
assertThat(mapper.getMappedExample(of(probe), context.getRequiredPersistentEntity(FlatDocument.class)))
.containsEntry("listOfString", list);
}
@Test // DATAMONGO-1245
@@ -139,10 +126,8 @@ public class MongoExampleMapperUnitTests {
FlatDocument probe = new FlatDocument();
probe.customNamedField = "Mitosis";
IsBsonObject<Bson> expected = isBsonObject().containing("custom_field_name", "Mitosis");
assertThat(mapper.getMappedExample(of(probe), context.getRequiredPersistentEntity(FlatDocument.class)),
is(expected));
assertThat(mapper.getMappedExample(of(probe), context.getRequiredPersistentEntity(FlatDocument.class)))
.containsEntry("custom_field_name", "Mitosis");
}
@Test // DATAMONGO-1245
@@ -155,8 +140,8 @@ public class MongoExampleMapperUnitTests {
org.bson.Document document = mapper.getMappedExample(Example.of(probe),
context.getRequiredPersistentEntity(WrapperDocument.class));
assertThat(document,
isBsonObject().containing("_class", new org.bson.Document("$in", new String[] { probe.getClass().getName() })));
assertThat(document).containsEntry("_class",
new org.bson.Document("$in", Collections.singletonList(probe.getClass().getName())));
}
@Test // DATAMONGO-1245
@@ -166,10 +151,8 @@ public class MongoExampleMapperUnitTests {
probe.flatDoc = new FlatDocument();
probe.flatDoc.stringValue = "conflux";
IsBsonObject<Bson> expected = isBsonObject().containing("flatDoc\\.stringValue", "conflux");
assertThat(mapper.getMappedExample(of(probe), context.getRequiredPersistentEntity(WrapperDocument.class)),
is(expected));
assertThat(mapper.getMappedExample(of(probe), context.getRequiredPersistentEntity(WrapperDocument.class)))
.containsEntry("flatDoc\\.stringValue", "conflux");
}
@Test // DATAMONGO-1245
@@ -181,8 +164,8 @@ public class MongoExampleMapperUnitTests {
Example<?> example = Example.of(probe, matching().withIncludeNullValues());
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(WrapperDocument.class)), //
isBsonObject().containing("flatDoc.stringValue", "conflux"));
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(WrapperDocument.class)))
.containsEntry("flatDoc.stringValue", "conflux");
}
@Test // DATAMONGO-1245
@@ -194,11 +177,9 @@ public class MongoExampleMapperUnitTests {
Example<?> example = Example.of(probe, matching().withStringMatcher(StringMatcher.STARTING));
IsBsonObject<Bson> expected = isBsonObject().//
containing("stringValue.$regex", "^firefight").//
containing("intValue", 100);
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(FlatDocument.class)), is(expected));
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(FlatDocument.class)))
.containsEntry("stringValue.$regex", "^firefight")//
.containsEntry("intValue", 100);
}
@Test // DATAMONGO-1245
@@ -210,11 +191,9 @@ public class MongoExampleMapperUnitTests {
Example<?> example = Example.of(probe, matching().withStringMatcher(StringMatcher.STARTING));
IsBsonObject<Bson> expected = isBsonObject().//
containing("stringValue.$regex", "^" + Pattern.quote("fire.ight")).//
containing("intValue", 100);
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(FlatDocument.class)), is(expected));
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(FlatDocument.class)))
.containsEntry("stringValue.$regex", "^" + Pattern.quote("fire.ight"))//
.containsEntry("intValue", 100);
}
@Test // DATAMONGO-1245
@@ -226,11 +205,9 @@ public class MongoExampleMapperUnitTests {
Example<?> example = Example.of(probe, matching().withStringMatcher(StringMatcher.ENDING));
IsBsonObject<Bson> expected = isBsonObject().//
containing("stringValue.$regex", "firefight$").//
containing("intValue", 100);
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(FlatDocument.class)), is(expected));
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(FlatDocument.class)))
.containsEntry("stringValue.$regex", "firefight$") //
.containsEntry("intValue", 100);
}
@Test // DATAMONGO-1245
@@ -242,11 +219,9 @@ public class MongoExampleMapperUnitTests {
Example<?> example = Example.of(probe, matching().withStringMatcher(StringMatcher.REGEX));
IsBsonObject<Bson> expected = isBsonObject().//
containing("stringValue.$regex", "firefight").//
containing("custom_field_name.$regex", "^(cat|dog).*shelter\\d?");
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(FlatDocument.class)), is(expected));
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(FlatDocument.class)))
.containsEntry("stringValue.$regex", "firefight") //
.containsEntry("custom_field_name.$regex", "^(cat|dog).*shelter\\d?");
}
@Test // DATAMONGO-1245
@@ -258,11 +233,9 @@ public class MongoExampleMapperUnitTests {
Example<?> example = Example.of(probe, matching().withStringMatcher(StringMatcher.ENDING).withIgnoreCase());
IsBsonObject<Bson> expected = isBsonObject().//
containing("stringValue", new org.bson.Document("$regex", "firefight$").append("$options", "i")).//
containing("intValue", 100);
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(FlatDocument.class)), is(expected));
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(FlatDocument.class)))
.containsEntry("stringValue", new org.bson.Document("$regex", "firefight$").append("$options", "i")) //
.containsEntry("intValue", 100);
}
@Test // DATAMONGO-1245
@@ -274,11 +247,10 @@ public class MongoExampleMapperUnitTests {
Example<?> example = Example.of(probe, matching().withIgnoreCase());
IsBsonObject<Bson> expected = isBsonObject().//
containing("stringValue", new org.bson.Document("$regex", Pattern.quote("firefight")).append("$options", "i")).//
containing("intValue", 100);
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(FlatDocument.class)), is(expected));
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(FlatDocument.class)))
.containsEntry("stringValue",
new org.bson.Document("$regex", Pattern.quote("firefight")).append("$options", "i")) //
.containsEntry("intValue", 100);
}
@Test // DATAMONGO-1245
@@ -293,8 +265,8 @@ public class MongoExampleMapperUnitTests {
context.getRequiredPersistentEntity(WithDBRef.class));
com.mongodb.DBRef reference = getTypedValue(document, "referenceDocument", com.mongodb.DBRef.class);
assertThat(reference.getId(), Is.<Object> is("200"));
assertThat(reference.getCollectionName(), is("refDoc"));
assertThat(reference.getId()).isEqualTo("200");
assertThat(reference.getCollectionName()).isEqualTo("refDoc");
}
@Test // DATAMONGO-1245
@@ -306,7 +278,7 @@ public class MongoExampleMapperUnitTests {
org.bson.Document document = mapper.getMappedExample(of(probe),
context.getRequiredPersistentEntity(FlatDocument.class));
assertThat(document, isBsonObject().containing("stringValue", "steelheart"));
assertThat(document).containsEntry("stringValue", "steelheart");
}
@Test // DATAMONGO-1245
@@ -318,8 +290,8 @@ public class MongoExampleMapperUnitTests {
org.bson.Document document = mapper.getMappedExample(of(probe),
context.getRequiredPersistentEntity(WithDBRef.class));
assertThat(document.get("legacyPoint.x"), Is.<Object> is(10D));
assertThat(document.get("legacyPoint.y"), Is.<Object> is(20D));
assertThat(document.get("legacyPoint.x")).isEqualTo(10D);
assertThat(document.get("legacyPoint.y")).isEqualTo(20D);
}
@Test // DATAMONGO-1245
@@ -332,11 +304,9 @@ public class MongoExampleMapperUnitTests {
Example<?> example = Example.of(probe, matching().withIgnorePaths("customNamedField"));
IsBsonObject<Bson> expected = isBsonObject().//
containing("stringValue", "string").//
containing("intValue", 10);
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(FlatDocument.class)), is(expected));
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(FlatDocument.class)))
.containsEntry("stringValue", "string") //
.containsEntry("intValue", 10);
}
@Test // DATAMONGO-1245
@@ -349,11 +319,9 @@ public class MongoExampleMapperUnitTests {
Example<?> example = Example.of(probe, matching().withIgnorePaths("stringValue"));
IsBsonObject<Bson> expected = isBsonObject().//
containing("custom_field_name", "foo").//
containing("intValue", 10);
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(FlatDocument.class)), is(expected));
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(FlatDocument.class)))
.containsEntry("custom_field_name", "foo") //
.containsEntry("intValue", 10);
}
@Test // DATAMONGO-1245
@@ -367,12 +335,9 @@ public class MongoExampleMapperUnitTests {
Example<?> example = Example.of(probe, matching().withIgnorePaths("flatDoc.stringValue"));
IsBsonObject<Bson> expected = isBsonObject().//
containing("flatDoc\\.custom_field_name", "foo").//
containing("flatDoc\\.intValue", 10);
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(WrapperDocument.class)),
is(expected));
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(WrapperDocument.class)))
.containsEntry("flatDoc\\.custom_field_name", "foo")//
.containsEntry("flatDoc\\.intValue", 10);
}
@Test // DATAMONGO-1245
@@ -386,12 +351,9 @@ public class MongoExampleMapperUnitTests {
Example<?> example = Example.of(probe, matching().withIgnorePaths("flatDoc.customNamedField"));
IsBsonObject<Bson> expected = isBsonObject().//
containing("flatDoc\\.stringValue", "string").//
containing("flatDoc\\.intValue", 10);
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(WrapperDocument.class)),
is(expected));
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(WrapperDocument.class)))
.containsEntry("flatDoc\\.stringValue", "string") //
.containsEntry("flatDoc\\.intValue", 10);
}
@Test // DATAMONGO-1245
@@ -403,11 +365,9 @@ public class MongoExampleMapperUnitTests {
Example<?> example = Example.of(probe, matching().withMatcher("stringValue", GenericPropertyMatchers.contains()));
IsBsonObject<Bson> expected = isBsonObject().//
containing("stringValue.$regex", ".*firefight.*").//
containing("custom_field_name", "steelheart");
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(FlatDocument.class)), is(expected));
assertThat(mapper.getMappedExample(example, context.getRequiredPersistentEntity(FlatDocument.class)))
.containsEntry("stringValue.$regex", ".*firefight.*") //
.containsEntry("custom_field_name", "steelheart");
}
@Test // DATAMONGO-1245
@@ -421,7 +381,7 @@ public class MongoExampleMapperUnitTests {
org.bson.Document document = mapper.getMappedExample(of(probe),
context.getRequiredPersistentEntity(FlatDocument.class));
assertThat(document, isBsonObject().containing("anotherStringValue", "calamity"));
assertThat(document).containsEntry("anotherStringValue", "calamity");
}
@Test // DATAMONGO-1459
@@ -433,7 +393,7 @@ public class MongoExampleMapperUnitTests {
Example<FlatDocument> example = Example.of(probe, ExampleMatcher.matchingAny());
assertThat(mapper.getMappedExample(example), isBsonObject().containing("$or").containing("_class"));
assertThat(mapper.getMappedExample(example)).containsKeys("$or", "_class");
}
@Test // DATAMONGO-1768
@@ -446,7 +406,7 @@ public class MongoExampleMapperUnitTests {
org.bson.Document document = mapper
.getMappedExample(Example.of(probe, ExampleMatcher.matching().withIgnorePaths("_class")));
assertThat(document, isBsonObject().notContaining("_class"));
assertThat(document).doesNotContainKey("_class");
}
@Test // DATAMONGO-1768
@@ -480,7 +440,7 @@ public class MongoExampleMapperUnitTests {
org.bson.Document document = new MongoExampleMapper(mappingMongoConverter)
.getMappedExample(Example.of(probe, ExampleMatcher.matching().withIgnorePaths("_foo")));
assertThat(document, isBsonObject().notContaining("_class").notContaining("_foo"));
assertThat(document).doesNotContainKeys("_class", "_foo");
}
@Test // DATAMONGO-1768
@@ -491,7 +451,7 @@ public class MongoExampleMapperUnitTests {
probe.flatDoc.stringValue = "conflux";
org.bson.Document document = mapper.getMappedExample(Example.of(probe, UntypedExampleMatcher.matching()));
assertThat(document, isBsonObject().notContaining("_class"));
assertThat(document).doesNotContainKey("_class");
}
static class FlatDocument {

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core.convert;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.test.util.Assertions.*;
import org.bson.Document;
import org.bson.types.Code;
@@ -24,6 +23,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.core.convert.MongoConverters.DocumentToNamedMongoScriptConverter;
import org.springframework.data.mongodb.core.convert.MongoConverters.NamedMongoScriptToDocumentConverter;
@@ -39,7 +39,8 @@ import org.springframework.data.mongodb.core.script.NamedMongoScript;
* @since 1.7
*/
@RunWith(Suite.class)
@SuiteClasses({ NamedMongoScriptToDocumentConverterUnitTests.class, DocumentToNamedMongoScriptConverterUnitTests.class })
@SuiteClasses({ NamedMongoScriptToDocumentConverterUnitTests.class,
DocumentToNamedMongoScriptConverterUnitTests.class })
public class NamedMongoScriptConvertsUnitTests {
static final String FUNCTION_NAME = "echo";
@@ -57,7 +58,7 @@ public class NamedMongoScriptConvertsUnitTests {
@Test // DATAMONGO-479
public void convertShouldReturnEmptyDocWhenScriptIsNull() {
assertThat(converter.convert(null), is((Document) new Document()));
assertThat(converter.convert(null)).isEqualTo(new Document());
}
@Test // DATAMONGO-479
@@ -66,8 +67,7 @@ public class NamedMongoScriptConvertsUnitTests {
Document document = converter.convert(ECHO_SCRIPT);
Object id = document.get("_id");
assertThat(id, is(instanceOf(String.class)));
assertThat(id, is((Object) FUNCTION_NAME));
assertThat(id).isInstanceOf(String.class).isEqualTo(FUNCTION_NAME);
}
@Test // DATAMONGO-479
@@ -76,8 +76,7 @@ public class NamedMongoScriptConvertsUnitTests {
Document document = converter.convert(ECHO_SCRIPT);
Object code = document.get("value");
assertThat(code, is(instanceOf(Code.class)));
assertThat(code, is((Object) new Code(JS_FUNCTION)));
assertThat(code).isInstanceOf(Code.class).isEqualTo(new Code(JS_FUNCTION));
}
}
@@ -90,7 +89,7 @@ public class NamedMongoScriptConvertsUnitTests {
@Test // DATAMONGO-479
public void convertShouldReturnNullIfSourceIsNull() {
assertThat(converter.convert(null), is(nullValue()));
assertThat(converter.convert(null)).isNull();
}
@Test // DATAMONGO-479
@@ -98,7 +97,7 @@ public class NamedMongoScriptConvertsUnitTests {
NamedMongoScript script = converter.convert(FUNCTION);
assertThat(script.getName(), is(FUNCTION_NAME));
assertThat(script.getName()).isEqualTo(FUNCTION_NAME);
}
@Test // DATAMONGO-479
@@ -106,8 +105,7 @@ public class NamedMongoScriptConvertsUnitTests {
NamedMongoScript script = converter.convert(FUNCTION);
assertThat(script.getCode(), is(notNullValue()));
assertThat(script.getCode(), is(JS_FUNCTION));
assertThat(script.getCode()).isEqualTo(JS_FUNCTION);
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core.convert;
import static org.hamcrest.core.Is.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Arrays;
import java.util.Collection;
@@ -28,6 +27,7 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.springframework.data.mongodb.core.convert.MongoConverters.NumberToNumberConverterFactory;
/**
@@ -54,6 +54,7 @@ public class NumberToNumberConverterFactoryUnitTests {
@Test // DATAMONGO-1288
public void convertsToTargetTypeCorrectly() {
assertThat(NumberToNumberConverterFactory.INSTANCE.getConverter(expected.getClass()).convert(source), is(expected));
assertThat(NumberToNumberConverterFactory.INSTANCE.getConverter(expected.getClass()).convert(source))
.isEqualTo(expected);
}
}

View File

@@ -15,11 +15,11 @@
*/
package org.springframework.data.mongodb.core.convert;
import static org.hamcrest.core.IsNull.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.springframework.data.mongodb.core.convert.MongoConverters.TermToStringConverter;
import org.springframework.data.mongodb.core.query.Term;
import org.springframework.data.mongodb.core.query.Term.Type;
@@ -31,7 +31,7 @@ public class TermToStringConverterUnitTests {
@Test // DATAMONGO-973
public void shouldNotConvertNull() {
assertThat(TermToStringConverter.INSTANCE.convert(null), nullValue());
assertThat(TermToStringConverter.INSTANCE.convert(null)).isNull();
}
@Test // DATAMONGO-973

View File

@@ -15,14 +15,14 @@
*/
package org.springframework.data.mongodb.core.geo;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.io.IOException;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.geo.Point;
import com.fasterxml.jackson.core.JsonParseException;
@@ -48,7 +48,7 @@ public class GeoJsonModuleUnitTests {
String json = "{ \"type\": \"Point\", \"coordinates\": [10.0, 20.0] }";
assertThat(mapper.readValue(json, GeoJsonPoint.class), is(new GeoJsonPoint(10D, 20D)));
assertThat(mapper.readValue(json, GeoJsonPoint.class)).isEqualTo(new GeoJsonPoint(10D, 20D));
}
@Test // DATAMONGO-1181
@@ -57,8 +57,8 @@ public class GeoJsonModuleUnitTests {
String json = "{ \"type\": \"LineString\", \"coordinates\": [ [10.0, 20.0], [30.0, 40.0], [50.0, 60.0] ]}";
assertThat(mapper.readValue(json, GeoJsonLineString.class),
is(new GeoJsonLineString(Arrays.asList(new Point(10, 20), new Point(30, 40), new Point(50, 60)))));
assertThat(mapper.readValue(json, GeoJsonLineString.class))
.isEqualTo(new GeoJsonLineString(Arrays.asList(new Point(10, 20), new Point(30, 40), new Point(50, 60))));
}
@Test // DATAMONGO-1181
@@ -67,8 +67,8 @@ public class GeoJsonModuleUnitTests {
String json = "{ \"type\": \"MultiPoint\", \"coordinates\": [ [10.0, 20.0], [30.0, 40.0], [50.0, 60.0] ]}";
assertThat(mapper.readValue(json, GeoJsonLineString.class),
is(new GeoJsonMultiPoint(Arrays.asList(new Point(10, 20), new Point(30, 40), new Point(50, 60)))));
assertThat(mapper.readValue(json, GeoJsonLineString.class))
.isEqualTo(new GeoJsonMultiPoint(Arrays.asList(new Point(10, 20), new Point(30, 40), new Point(50, 60))));
}
@Test // DATAMONGO-1181
@@ -78,10 +78,8 @@ public class GeoJsonModuleUnitTests {
String json = "{ \"type\": \"MultiLineString\", \"coordinates\": [ [ [10.0, 20.0], [30.0, 40.0] ], [ [50.0, 60.0] , [70.0, 80.0] ] ]}";
assertThat(
mapper.readValue(json, GeoJsonMultiLineString.class),
is(new GeoJsonMultiLineString(Arrays.asList(new Point(10, 20), new Point(30, 40)), Arrays.asList(new Point(50,
60), new Point(70, 80)))));
assertThat(mapper.readValue(json, GeoJsonMultiLineString.class)).isEqualTo(new GeoJsonMultiLineString(
Arrays.asList(new Point(10, 20), new Point(30, 40)), Arrays.asList(new Point(50, 60), new Point(70, 80))));
}
@Test // DATAMONGO-1181
@@ -89,10 +87,8 @@ public class GeoJsonModuleUnitTests {
String json = "{ \"type\": \"Polygon\", \"coordinates\": [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] ]}";
assertThat(
mapper.readValue(json, GeoJsonPolygon.class),
is(new GeoJsonPolygon(Arrays.asList(new Point(100, 0), new Point(101, 0), new Point(101, 1), new Point(100, 1),
new Point(100, 0)))));
assertThat(mapper.readValue(json, GeoJsonPolygon.class)).isEqualTo(new GeoJsonPolygon(
Arrays.asList(new Point(100, 0), new Point(101, 0), new Point(101, 1), new Point(100, 1), new Point(100, 0))));
}
@Test // DATAMONGO-1181
@@ -105,15 +101,13 @@ public class GeoJsonModuleUnitTests {
+ "[[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]]"//
+ "]}";
assertThat(
mapper.readValue(json, GeoJsonMultiPolygon.class),
is(new GeoJsonMultiPolygon(Arrays.asList(
new GeoJsonPolygon(Arrays.asList(new Point(102, 2), new Point(103, 2), new Point(103, 3),
new Point(102, 3), new Point(102, 2))),
new GeoJsonPolygon(Arrays.asList(new Point(100, 0), new Point(101, 0), new Point(101, 1),
new Point(100, 1), new Point(100, 0))),
new GeoJsonPolygon(Arrays.asList(new Point(100.2, 0.2), new Point(100.8, 0.2), new Point(100.8, 0.8),
new Point(100.2, 0.8), new Point(100.2, 0.2)))))));
assertThat(mapper.readValue(json, GeoJsonMultiPolygon.class)).isEqualTo(new GeoJsonMultiPolygon(Arrays.asList(
new GeoJsonPolygon(Arrays.asList(new Point(102, 2), new Point(103, 2), new Point(103, 3), new Point(102, 3),
new Point(102, 2))),
new GeoJsonPolygon(Arrays.asList(new Point(100, 0), new Point(101, 0), new Point(101, 1), new Point(100, 1),
new Point(100, 0))),
new GeoJsonPolygon(Arrays.asList(new Point(100.2, 0.2), new Point(100.8, 0.2), new Point(100.8, 0.8),
new Point(100.2, 0.8), new Point(100.2, 0.2))))));
}
}

View File

@@ -16,25 +16,25 @@
package org.springframework.data.mongodb.core.geo;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.core.query.Query.*;
import java.util.List;
import org.junit.Test;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Metrics;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.Venue;
import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;
import org.springframework.data.mongodb.core.index.GeospatialIndex;
import org.springframework.data.mongodb.core.index.IndexField;
import org.springframework.data.mongodb.core.index.IndexInfo;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.query.NearQuery;
/**
@@ -48,15 +48,15 @@ public class GeoSpatial2DSphereTests extends AbstractGeoSpatialTests {
IndexOperations operations = template.indexOps(Venue.class);
List<IndexInfo> indexInfo = operations.getIndexInfo();
assertThat(indexInfo.size(), is(2));
assertThat(indexInfo.size()).isEqualTo(2);
List<IndexField> fields = indexInfo.get(0).getIndexFields();
assertThat(fields.size(), is(1));
assertThat(fields, hasItem(IndexField.create("_id", Direction.ASC)));
assertThat(fields.size()).isEqualTo(1);
assertThat(fields).contains(IndexField.create("_id", Direction.ASC));
fields = indexInfo.get(1).getIndexFields();
assertThat(fields.size(), is(1));
assertThat(fields, hasItem(IndexField.geo("location")));
assertThat(fields.size()).isEqualTo(1);
assertThat(fields).contains(IndexField.geo("location"));
}
@Test // DATAMONGO-1110
@@ -66,15 +66,15 @@ public class GeoSpatial2DSphereTests extends AbstractGeoSpatialTests {
GeoResults<Venue> result = template.geoNear(geoNear, Venue.class);
assertThat(result.getContent().size(), is(not(0)));
assertThat(result.getAverageDistance().getMetric(), is((Metric) Metrics.KILOMETERS));
assertThat(result.getContent().size()).isNotEqualTo(0);
assertThat(result.getAverageDistance().getMetric()).isEqualTo((Metric) Metrics.KILOMETERS);
}
@Test // DATAMONGO-1110
public void nearSphereWithMinDistance() {
Point point = new Point(-73.99171, 40.738868);
List<Venue> venues = template.find(query(where("location").nearSphere(point).minDistance(0.01)), Venue.class);
assertThat(venues.size(), is(1));
assertThat(venues.size()).isEqualTo(1);
}
@Override

View File

@@ -16,22 +16,22 @@
package org.springframework.data.mongodb.core.geo;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.core.query.Query.*;
import java.util.List;
import org.junit.Test;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.Venue;
import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;
import org.springframework.data.mongodb.core.index.GeospatialIndex;
import org.springframework.data.mongodb.core.index.IndexField;
import org.springframework.data.mongodb.core.index.IndexInfo;
import org.springframework.data.mongodb.core.index.IndexOperations;
/**
* Modified from https://github.com/deftlabs/mongo-java-geospatial-example
@@ -47,7 +47,7 @@ public class GeoSpatial2DTests extends AbstractGeoSpatialTests {
public void nearPoint() {
Point point = new Point(-73.99171, 40.738868);
List<Venue> venues = template.find(query(where("location").near(point).maxDistance(0.01)), Venue.class);
assertThat(venues.size(), is(7));
assertThat(venues.size()).isEqualTo(7);
}
@Test // DATAMONGO-360
@@ -56,15 +56,15 @@ public class GeoSpatial2DTests extends AbstractGeoSpatialTests {
IndexOperations operations = template.indexOps(Venue.class);
List<IndexInfo> indexInfo = operations.getIndexInfo();
assertThat(indexInfo.size(), is(2));
assertThat(indexInfo.size()).isEqualTo(2);
List<IndexField> fields = indexInfo.get(0).getIndexFields();
assertThat(fields.size(), is(1));
assertThat(fields, hasItem(IndexField.create("_id", Direction.ASC)));
assertThat(fields.size()).isEqualTo(1);
assertThat(fields).contains(IndexField.create("_id", Direction.ASC));
fields = indexInfo.get(1).getIndexFields();
assertThat(fields.size(), is(1));
assertThat(fields, hasItem(IndexField.geo("location")));
assertThat(fields.size()).isEqualTo(1);
assertThat(fields).contains(IndexField.geo("location"));
}
@Override

View File

@@ -15,14 +15,11 @@
*/
package org.springframework.data.mongodb.core.index;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import org.hamcrest.Matchers;
import org.hamcrest.core.IsInstanceOf;
import org.junit.ClassRule;
import org.junit.Rule;
@@ -30,6 +27,7 @@ import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.RuleChain;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataIntegrityViolationException;
@@ -76,11 +74,11 @@ public class MongoPersistentEntityIndexCreatorIntegrationTests {
public void createsIndexForConfiguredMappingContextOnly() {
List<IndexInfo> indexInfo = templateOne.indexOps(SampleEntity.class).getIndexInfo();
assertThat(indexInfo, hasSize(greaterThan(0)));
assertThat(indexInfo, Matchers.<IndexInfo> hasItem(hasProperty("name", is("prop"))));
assertThat(indexInfo).isNotEmpty();
assertThat(indexInfo).extracting(IndexInfo::getName).contains("prop");
indexInfo = templateTwo.indexOps(SAMPLE_TYPE_COLLECTION_NAME).getIndexInfo();
assertThat(indexInfo, hasSize(0));
assertThat(indexInfo).hasSize(0);
}
@Test // DATAMONGO-1202
@@ -88,12 +86,12 @@ public class MongoPersistentEntityIndexCreatorIntegrationTests {
List<IndexInfo> indexInfo = templateOne.indexOps(RecursiveConcreteType.class).getIndexInfo();
assertThat(indexInfo, hasSize(greaterThan(0)));
assertThat(indexInfo, Matchers.<IndexInfo> hasItem(hasProperty("name", is("firstName"))));
assertThat(indexInfo).isNotEmpty();
assertThat(indexInfo).extracting(IndexInfo::getName).contains("firstName");
}
@Test // DATAMONGO-1125
public void createIndexShouldThrowMeaningfulExceptionWhenIndexCreationFails() throws UnknownHostException {
public void createIndexShouldThrowMeaningfulExceptionWhenIndexCreationFails() {
expectedException.expect(DataIntegrityViolationException.class);
expectedException.expectMessage("collection 'datamongo-1125'");

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core.index;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.Before;
@@ -25,6 +24,7 @@ import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexResolver.CycleGuard.Path;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
@@ -54,9 +54,9 @@ public class PathUnitTests {
Path path = Path.of(foo).append(bar).append(bar);
assertThat(path.isCycle(), is(true));
assertThat(path.toCyclePath(), is(equalTo("bar -> bar")));
assertThat(path.toString(), is(equalTo("foo -> bar -> bar")));
assertThat(path.isCycle()).isTrue();
assertThat(path.toCyclePath()).isEqualTo("bar -> bar");
assertThat(path.toString()).isEqualTo("foo -> bar -> bar");
}
@Test // DATAMONGO-1782
@@ -67,9 +67,9 @@ public class PathUnitTests {
Path path = Path.of(foo).append(bar);
assertThat(path.isCycle(), is(false));
assertThat(path.toCyclePath(), is(equalTo("")));
assertThat(path.toString(), is(equalTo("foo -> bar")));
assertThat(path.isCycle()).isFalse();
assertThat(path.toCyclePath()).isEqualTo("");
assertThat(path.toString()).isEqualTo("foo -> bar");
}
@Test // DATAMONGO-1782
@@ -79,7 +79,7 @@ public class PathUnitTests {
MongoPersistentProperty bar = createPersistentPropertyMock(entityMock, "bar");
MongoPersistentProperty bar2 = createPersistentPropertyMock(mock(MongoPersistentEntity.class), "bar");
assertThat(Path.of(foo).append(bar).append(bar2).isCycle(), is(false));
assertThat(Path.of(foo).append(bar).append(bar2).isCycle()).isFalse();
}
@SuppressWarnings({ "rawtypes", "unchecked" })

View File

@@ -15,9 +15,7 @@
*/
package org.springframework.data.mongodb.core.mapping;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.Assertions.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
@@ -33,6 +31,7 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.core.annotation.AliasFor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mapping.MappingException;
@@ -66,22 +65,22 @@ public class BasicMongoPersistentPropertyUnitTests {
public void usesAnnotatedFieldName() {
Field field = ReflectionUtils.findField(Person.class, "firstname");
assertThat(getPropertyFor(field).getFieldName(), is("foo"));
assertThat(getPropertyFor(field).getFieldName()).isEqualTo("foo");
}
@Test
public void returns_IdForIdProperty() {
Field field = ReflectionUtils.findField(Person.class, "id");
MongoPersistentProperty property = getPropertyFor(field);
assertThat(property.isIdProperty(), is(true));
assertThat(property.getFieldName(), is("_id"));
assertThat(property.isIdProperty()).isTrue();
assertThat(property.getFieldName()).isEqualTo("_id");
}
@Test
public void returnsPropertyNameForUnannotatedProperties() {
Field field = ReflectionUtils.findField(Person.class, "lastname");
assertThat(getPropertyFor(field).getFieldName(), is("lastname"));
assertThat(getPropertyFor(field).getFieldName()).isEqualTo("lastname");
}
@Test
@@ -96,7 +95,7 @@ public class BasicMongoPersistentPropertyUnitTests {
ClassTypeInformation.from(Throwable.class));
MongoPersistentProperty property = getPropertyFor(entity, "cause");
assertThat(property.usePropertyAccess(), is(true));
assertThat(property.usePropertyAccess()).isTrue();
}
@Test // DATAMONGO-607
@@ -107,13 +106,13 @@ public class BasicMongoPersistentPropertyUnitTests {
MongoPersistentProperty property = new BasicMongoPersistentProperty(Property.of(type, field), entity,
SimpleTypeHolder.DEFAULT, UppercaseFieldNamingStrategy.INSTANCE);
assertThat(property.getFieldName(), is("LASTNAME"));
assertThat(property.getFieldName()).isEqualTo("LASTNAME");
field = ReflectionUtils.findField(Person.class, "firstname");
property = new BasicMongoPersistentProperty(Property.of(type, field), entity, SimpleTypeHolder.DEFAULT,
UppercaseFieldNamingStrategy.INSTANCE);
assertThat(property.getFieldName(), is("foo"));
assertThat(property.getFieldName()).isEqualTo("foo");
}
@Test // DATAMONGO-607
@@ -136,35 +135,35 @@ public class BasicMongoPersistentPropertyUnitTests {
public void shouldDetectAnnotatedLanguagePropertyCorrectly() {
MongoPersistentProperty property = getPropertyFor(DocumentWithLanguageProperty.class, "lang");
assertThat(property.isLanguageProperty(), is(true));
assertThat(property.isLanguageProperty()).isTrue();
}
@Test // DATAMONGO-937
public void shouldDetectIplicitLanguagePropertyCorrectly() {
MongoPersistentProperty property = getPropertyFor(DocumentWithImplicitLanguageProperty.class, "language");
assertThat(property.isLanguageProperty(), is(true));
assertThat(property.isLanguageProperty()).isTrue();
}
@Test // DATAMONGO-976
public void shouldDetectTextScorePropertyCorrectly() {
MongoPersistentProperty property = getPropertyFor(DocumentWithTextScoreProperty.class, "score");
assertThat(property.isTextScoreProperty(), is(true));
assertThat(property.isTextScoreProperty()).isTrue();
}
@Test // DATAMONGO-976
public void shouldDetectTextScoreAsReadOnlyProperty() {
MongoPersistentProperty property = getPropertyFor(DocumentWithTextScoreProperty.class, "score");
assertThat(property.isWritable(), is(false));
assertThat(property.isWritable()).isFalse();
}
@Test // DATAMONGO-1050
public void shouldNotConsiderExplicitlyNameFieldAsIdProperty() {
MongoPersistentProperty property = getPropertyFor(DocumentWithExplicitlyRenamedIdProperty.class, "id");
assertThat(property.isIdProperty(), is(false));
assertThat(property.isIdProperty()).isFalse();
}
@Test // DATAMONGO-1050
@@ -172,22 +171,22 @@ public class BasicMongoPersistentPropertyUnitTests {
MongoPersistentProperty property = getPropertyFor(DocumentWithExplicitlyRenamedIdPropertyHavingIdAnnotation.class,
"id");
assertThat(property.isIdProperty(), is(true));
assertThat(property.isIdProperty()).isTrue();
}
@Test // DATAMONGO-1373
public void shouldConsiderComposedAnnotationsForIdField() {
MongoPersistentProperty property = getPropertyFor(DocumentWithComposedAnnotations.class, "myId");
assertThat(property.isIdProperty(), is(true));
assertThat(property.getFieldName(), is("_id"));
assertThat(property.isIdProperty()).isTrue();
assertThat(property.getFieldName()).isEqualTo("_id");
}
@Test // DATAMONGO-1373
public void shouldConsiderComposedAnnotationsForFields() {
MongoPersistentProperty property = getPropertyFor(DocumentWithComposedAnnotations.class, "myField");
assertThat(property.getFieldName(), is("myField"));
assertThat(property.getFieldName()).isEqualTo("myField");
}
@Test // DATAMONGO-1737

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core.mapping;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Collections;
@@ -26,6 +25,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoConverter;
@@ -64,12 +64,12 @@ public class GenericMappingTests {
converter.write(wrapper, document);
Object container = document.get("container");
assertThat(container, is(notNullValue()));
assertTrue(container instanceof Document);
assertThat(container).isNotNull();
assertThat(container instanceof Document).isTrue();
Object content = ((Document) container).get("content");
assertTrue(content instanceof String);
assertThat((String) content, is("Foo!"));
assertThat(content instanceof String).isTrue();
assertThat((String) content).isEqualTo("Foo!");
}
@Test
@@ -79,8 +79,8 @@ public class GenericMappingTests {
Document container = new Document("container", content);
StringWrapper result = converter.read(StringWrapper.class, container);
assertThat(result.container, is(notNullValue()));
assertThat(result.container.content, is("Foo!"));
assertThat(result.container).isNotNull();
assertThat(result.container.content).isEqualTo("Foo!");
}
static class StringWrapper extends Wrapper<String> {

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core.mapping;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
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.Update.*;
@@ -28,8 +27,10 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;
@@ -43,7 +44,6 @@ import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.bson.Document;
import com.mongodb.MongoException;
import com.mongodb.client.MongoCollection;
@@ -62,7 +62,7 @@ public class MappingTests extends AbstractIntegrationTests {
GeneratedId genId = new GeneratedId("test");
template.insert(genId);
assertNotNull(genId.getId());
assertThat(genId.getId()).isNotNull();
}
@Test
@@ -70,12 +70,12 @@ public class MappingTests extends AbstractIntegrationTests {
PersonWithObjectId p = new PersonWithObjectId(12345, "Person", "Pojo");
template.insert(p);
assertNotNull(p.getId());
assertThat(p.getId()).isNotNull();
List<PersonWithObjectId> result = template.find(new Query(Criteria.where("ssn").is(12345)),
PersonWithObjectId.class);
assertThat(result.size(), is(1));
assertThat(result.get(0).getSsn(), is(12345));
assertThat(result.size()).isEqualTo(1);
assertThat(result.get(0).getSsn()).isEqualTo(12345);
}
@Test
@@ -86,24 +86,24 @@ public class MappingTests extends AbstractIntegrationTests {
List<PersonCustomIdName> result = template.find(new Query(Criteria.where("lastName").is(p.getLastName())),
PersonCustomIdName.class);
assertThat(result.size(), is(1));
assertThat(result.get(0).getFirstName(), is("Custom Id"));
assertThat(result.size()).isEqualTo(1);
assertThat(result.get(0).getFirstName()).isEqualTo("Custom Id");
PersonCustomIdName p2 = new PersonCustomIdName(654321, "Custom Id", "LastName");
template.insert(p2);
List<PersonCustomIdName> result2 = template.find(new Query(Criteria.where("lastName").is("LastName")),
PersonCustomIdName.class);
assertThat(result2.size(), is(1));
assertNotNull(result2.get(0).getLastName());
assertThat(result2.get(0).getLastName(), is("LastName"));
assertThat(result2.size()).isEqualTo(1);
assertThat(result2.get(0).getLastName()).isNotNull();
assertThat(result2.get(0).getLastName()).isEqualTo("LastName");
// Test "in" query
List<PersonCustomIdName> result3 = template.find(new Query(Criteria.where("lastName").in("LastName")),
PersonCustomIdName.class);
assertThat(result3.size(), is(1));
assertNotNull(result3.get(0).getLastName());
assertThat(result3.get(0).getLastName(), is("LastName"));
assertThat(result3.size()).isEqualTo(1);
assertThat(result3.get(0).getLastName()).isNotNull();
assertThat(result3.get(0).getLastName()).isEqualTo("LastName");
}
@Test
@@ -119,13 +119,13 @@ public class MappingTests extends AbstractIntegrationTests {
p.setAccounts(accounts);
template.insert(p);
assertNotNull(p.getId());
assertThat(p.getId()).isNotNull();
List<PersonMapProperty> result = template.find(new Query(Criteria.where("ssn").is(1234567)),
PersonMapProperty.class);
assertThat(result.size(), is(1));
assertThat(result.get(0).getAccounts().size(), is(2));
assertThat(result.get(0).getAccounts().get("checking").getBalance(), is(1000.0f));
assertThat(result.size()).isEqualTo(1);
assertThat(result.get(0).getAccounts().size()).isEqualTo(2);
assertThat(result.get(0).getAccounts().get("checking").getBalance()).isEqualTo(1000.0f);
}
@Test
@@ -156,12 +156,12 @@ public class MappingTests extends AbstractIntegrationTests {
accounts.add(newAcct);
template.save(p, "person");
assertNotNull(p.getId());
assertThat(p.getId()).isNotNull();
List<Person> result = template.find(new Query(Criteria.where("ssn").is(123456789)), Person.class);
assertThat(result.size(), is(1));
assertThat(result.get(0).getAddress().getCountry(), is("USA"));
assertThat(result.get(0).getAccounts(), notNullValue());
assertThat(result.size()).isEqualTo(1);
assertThat(result.get(0).getAddress().getCountry()).isEqualTo("USA");
assertThat(result.get(0).getAccounts()).isNotNull();
}
@Test(expected = DuplicateKeyException.class)
@@ -191,8 +191,8 @@ public class MappingTests extends AbstractIntegrationTests {
PersonCustomCollection1.class, "person1");
List<PersonCustomCollection2> p2Results = template.find(new Query(Criteria.where("ssn").is(66666)),
PersonCustomCollection2.class, "person2");
assertThat(p1Results.size(), is(1));
assertThat(p2Results.size(), is(1));
assertThat(p1Results.size()).isEqualTo(1);
assertThat(p2Results.size()).isEqualTo(1);
}
@Test
@@ -201,7 +201,7 @@ public class MappingTests extends AbstractIntegrationTests {
template.insert(loc);
List<Location> result = template.find(new Query(Criteria.where("_id").is(loc.getId())), Location.class, "places");
assertThat(result.size(), is(1));
assertThat(result.size()).isEqualTo(1);
}
@Test
@@ -209,7 +209,7 @@ public class MappingTests extends AbstractIntegrationTests {
CustomCollectionWithIndex ccwi = new CustomCollectionWithIndex("test");
template.insert(ccwi);
assertTrue(template.execute("foobar", new CollectionCallback<Boolean>() {
assertThat(template.execute("foobar", new CollectionCallback<Boolean>() {
public Boolean doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
List<Document> indexes = new ArrayList<Document>();
@@ -223,12 +223,12 @@ public class MappingTests extends AbstractIntegrationTests {
}
return false;
}
}));
})).isTrue();
DetectedCollectionWithIndex dcwi = new DetectedCollectionWithIndex("test");
template.insert(dcwi);
assertTrue(template.execute(MongoCollectionUtils.getPreferredCollectionName(DetectedCollectionWithIndex.class),
assertThat(template.execute(MongoCollectionUtils.getPreferredCollectionName(DetectedCollectionWithIndex.class),
new CollectionCallback<Boolean>() {
public Boolean doInCollection(MongoCollection<Document> collection)
throws MongoException, DataAccessException {
@@ -244,7 +244,7 @@ public class MappingTests extends AbstractIntegrationTests {
}
return false;
}
}));
})).isTrue();
}
@Test
@@ -256,9 +256,9 @@ public class MappingTests extends AbstractIntegrationTests {
template.insert(p);
List<PersonMultiDimArrays> result = template.find(new Query(Criteria.where("ssn").is(123)),
PersonMultiDimArrays.class);
assertThat(result.size(), is(1));
assertThat(result.size()).isEqualTo(1);
assertThat(result.get(0).getGrid().length, is(3));
assertThat(result.get(0).getGrid().length).isEqualTo(3);
}
@Test
@@ -276,9 +276,9 @@ public class MappingTests extends AbstractIntegrationTests {
List<PersonMultiCollection> result = template.find(new Query(Criteria.where("ssn").is(321)),
PersonMultiCollection.class);
assertThat(result.size(), is(1));
assertThat(result.size()).isEqualTo(1);
assertThat(result.get(0).getGrid().size(), is(1));
assertThat(result.get(0).getGrid().size()).isEqualTo(1);
}
@Test
@@ -291,8 +291,8 @@ public class MappingTests extends AbstractIntegrationTests {
template.insert(p);
List<PersonWithDbRef> result = template.find(new Query(Criteria.where("ssn").is(4321)), PersonWithDbRef.class);
assertThat(result.size(), is(1));
assertThat(result.get(0).getHome().getLocation(), is(pos));
assertThat(result.size()).isEqualTo(1);
assertThat(result.get(0).getHome().getLocation()).isEqualTo(pos);
}
@Test
@@ -300,7 +300,7 @@ public class MappingTests extends AbstractIntegrationTests {
PersonNullProperties p = new PersonNullProperties();
template.insert(p);
assertNotNull(p.getId());
assertThat(p.getId()).isNotNull();
}
@Test
@@ -319,7 +319,7 @@ public class MappingTests extends AbstractIntegrationTests {
template.updateFirst(query(where("ssn").is(1111)), update("address", addr), Person.class);
Person p2 = template.findOne(query(where("ssn").is(1111)), Person.class);
assertThat(p2.getAddress().getCity(), is("New Town"));
assertThat(p2.getAddress().getCity()).isEqualTo("New Town");
}
@Test
@@ -332,19 +332,19 @@ public class MappingTests extends AbstractIntegrationTests {
addr.setCountry("USA");
Person p2 = template.findOne(query(where("ssn").is(1111)), Person.class);
assertNull(p2);
assertThat(p2).isNull();
template.upsert(query(where("ssn").is(1111).and("firstName").is("Query").and("lastName").is("Update")),
update("address", addr), Person.class);
p2 = template.findOne(query(where("ssn").is(1111)), Person.class);
assertThat(p2.getAddress().getCity(), is("Anytown"));
assertThat(p2.getAddress().getCity()).isEqualTo("Anytown");
template.dropCollection(Person.class);
template.upsert(query(where("ssn").is(1111).and("firstName").is("Query").and("lastName").is("Update")),
update("address", addr), "person");
p2 = template.findOne(query(where("ssn").is(1111)), Person.class);
assertThat(p2.getAddress().getCity(), is("Anytown"));
assertThat(p2.getAddress().getCity()).isEqualTo("Anytown");
}
@@ -358,9 +358,9 @@ public class MappingTests extends AbstractIntegrationTests {
List<PersonWithObjectId> results = template
.find(new Query(new Criteria().orOperator(where("ssn").is(1), where("ssn").is(2))), PersonWithObjectId.class);
assertNotNull(results);
assertThat(results.size(), is(2));
assertThat(results.get(1).getSsn(), is(2));
assertThat(results).isNotNull();
assertThat(results.size()).isEqualTo(2);
assertThat(results.get(1).getSsn()).isEqualTo(2);
}
@Test
@@ -371,7 +371,7 @@ public class MappingTests extends AbstractIntegrationTests {
template.save(p);
PrimitiveId p2 = template.findOne(query(where("id").is(1)), PrimitiveId.class);
assertNotNull(p2);
assertThat(p2).isNotNull();
}
@Test
@@ -381,13 +381,13 @@ public class MappingTests extends AbstractIntegrationTests {
template.updateFirst(query(where("id").is(1)), update("text", "New Text"), PersonPojoIntId.class);
PersonPojoIntId p2 = template.findOne(query(where("id").is(1)), PersonPojoIntId.class);
assertEquals("New Text", p2.getText());
assertThat(p2.getText()).isEqualTo("New Text");
p.setText("Different Text");
template.save(p);
PersonPojoIntId p3 = template.findOne(query(where("id").is(1)), PersonPojoIntId.class);
assertEquals("Different Text", p3.getText());
assertThat(p3.getText()).isEqualTo("Different Text");
}
@@ -398,13 +398,13 @@ public class MappingTests extends AbstractIntegrationTests {
template.updateFirst(query(where("id").is(1)), update("text", "New Text"), PersonPojoLongId.class);
PersonPojoLongId p2 = template.findOne(query(where("id").is(1)), PersonPojoLongId.class);
assertEquals("New Text", p2.getText());
assertThat(p2.getText()).isEqualTo("New Text");
p.setText("Different Text");
template.save(p);
PersonPojoLongId p3 = template.findOne(query(where("id").is(1)), PersonPojoLongId.class);
assertEquals("Different Text", p3.getText());
assertThat(p3.getText()).isEqualTo("Different Text");
}
@@ -416,13 +416,13 @@ public class MappingTests extends AbstractIntegrationTests {
template.updateFirst(query(where("id").is("1")), update("text", "New Text"), PersonPojoStringId.class);
PersonPojoStringId p2 = template.findOne(query(where("id").is("1")), PersonPojoStringId.class);
assertEquals("New Text", p2.getText());
assertThat(p2.getText()).isEqualTo("New Text");
p.setText("Different Text");
template.save(p);
PersonPojoStringId p3 = template.findOne(query(where("id").is("1")), PersonPojoStringId.class);
assertEquals("Different Text", p3.getText());
assertThat(p3.getText()).isEqualTo("Different Text");
PersonPojoStringId p4 = new PersonPojoStringId("2", "Text-2");
template.insert(p4);
@@ -430,7 +430,7 @@ public class MappingTests extends AbstractIntegrationTests {
Query q = query(where("id").in("1", "2"));
q.with(Sort.by(Direction.ASC, "id"));
List<PersonPojoStringId> people = template.find(q, PersonPojoStringId.class);
assertEquals(2, people.size());
assertThat(people.size()).isEqualTo(2);
}
@@ -444,9 +444,9 @@ public class MappingTests extends AbstractIntegrationTests {
Query q = query(where("ssn").is(21));
PersonWithLongDBRef p2 = template.findOne(q, PersonWithLongDBRef.class);
assertNotNull(p2);
assertNotNull(p2.getPersonPojoLongId());
assertEquals(12L, p2.getPersonPojoLongId().getId());
assertThat(p2).isNotNull();
assertThat(p2.getPersonPojoLongId()).isNotNull();
assertThat(p2.getPersonPojoLongId().getId()).isEqualTo(12L);
}
@Test // DATADOC-275
@@ -467,9 +467,9 @@ public class MappingTests extends AbstractIntegrationTests {
template.insert(container);
Container result = template.findOne(query(where("id").is(container.id)), Container.class);
assertThat(result.item.id, is(item.id));
assertThat(result.items.size(), is(1));
assertThat(result.items.get(0).id, is(items.id));
assertThat(result.item.id).isEqualTo(item.id);
assertThat(result.items.size()).isEqualTo(1);
assertThat(result.items.get(0).id).isEqualTo(items.id);
}
@Test // DATAMONGO-805
@@ -490,8 +490,8 @@ public class MappingTests extends AbstractIntegrationTests {
query.fields().exclude("item");
Container result = template.findOne(query, Container.class);
assertThat(result, is(notNullValue()));
assertThat(result.item, is(nullValue()));
assertThat(result).isNotNull();
assertThat(result.item).isNull();
}
@Test // DATAMONGO-805
@@ -512,9 +512,9 @@ public class MappingTests extends AbstractIntegrationTests {
Query query = new Query(Criteria.where("id").is("foo"));
Container result = template.findOne(query, Container.class);
assertThat(result, is(notNullValue()));
assertThat(result.item, is(notNullValue()));
assertThat(result.item.value, is("bar"));
assertThat(result).isNotNull();
assertThat(result.item).isNotNull();
assertThat(result.item.value).isEqualTo("bar");
}
static class Container {

View File

@@ -1,7 +1,7 @@
package org.springframework.data.mongodb.core.mapping;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.Arrays;
import java.util.Collections;
@@ -11,14 +11,12 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity.MongoPersistentPropertyComparator;
import static org.mockito.Mockito.*;
import org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity.MongoPersistentPropertyComparator;
/**
* Unit tests for {@link MongoPersistentPropertyComparator}.
*
*
* @author Oliver Gierke
*/
@RunWith(MockitoJUnitRunner.class)
@@ -43,8 +41,8 @@ public class MongoPersistentPropertyComparatorUnitTests {
List<MongoPersistentProperty> properties = Arrays.asList(firstName, lastName, ssn);
Collections.sort(properties, MongoPersistentPropertyComparator.INSTANCE);
assertThat(properties.get(0), is(ssn));
assertThat(properties.get(1), is(firstName));
assertThat(properties.get(2), is(lastName));
assertThat(properties.get(0)).isEqualTo(ssn);
assertThat(properties.get(1)).isEqualTo(firstName);
assertThat(properties.get(2)).isEqualTo(lastName);
}
}

View File

@@ -15,11 +15,11 @@
*/
package org.springframework.data.mongodb.core.mapping.event;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.bson.Document;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.mongodb.core.mapping.Account;
@@ -40,7 +40,7 @@ public class AbstractMongoEventListenerUnitTests {
MongoMappingEvent<Person> event = new BeforeConvertEvent<Person>(new Person("Dave", "Matthews"), "collection-1");
SamplePersonEventListener listener = new SamplePersonEventListener();
listener.onApplicationEvent(event);
assertThat(listener.invokedOnBeforeConvert, is(true));
assertThat(listener.invokedOnBeforeConvert).isTrue();
}
@Test
@@ -53,11 +53,11 @@ public class AbstractMongoEventListenerUnitTests {
context.addApplicationListener(listener);
context.publishEvent(new BeforeConvertEvent<Person>(new Person("Dave", "Matthews"), "collection-1"));
assertThat(listener.invokedOnBeforeConvert, is(true));
assertThat(listener.invokedOnBeforeConvert).isTrue();
listener.invokedOnBeforeConvert = false;
context.publishEvent(new BeforeConvertEvent<String>("Test", "collection-1"));
assertThat(listener.invokedOnBeforeConvert, is(false));
assertThat(listener.invokedOnBeforeConvert).isFalse();
context.close();
}
@@ -67,7 +67,7 @@ public class AbstractMongoEventListenerUnitTests {
SamplePersonEventListener listener = new SamplePersonEventListener();
listener.onApplicationEvent(new AfterLoadEvent<Person>(new Document(), Person.class, "collection-1"));
assertThat(listener.invokedOnAfterLoad, is(true));
assertThat(listener.invokedOnAfterLoad).isTrue();
}
@Test // DATAMONGO-289
@@ -78,8 +78,8 @@ public class AbstractMongoEventListenerUnitTests {
personListener.onApplicationEvent(new AfterLoadEvent<Person>(new Document(), Person.class, "collection-1"));
accountListener.onApplicationEvent(new AfterLoadEvent<Person>(new Document(), Person.class, "collection-1"));
assertThat(personListener.invokedOnAfterLoad, is(true));
assertThat(accountListener.invokedOnAfterLoad, is(false));
assertThat(personListener.invokedOnAfterLoad).isTrue();
assertThat(accountListener.invokedOnAfterLoad).isFalse();
}
@Test // DATAMONGO-289
@@ -90,8 +90,8 @@ public class AbstractMongoEventListenerUnitTests {
personListener.onApplicationEvent(new AfterLoadEvent<Person>(new Document(), Person.class, "collection-1"));
contactListener.onApplicationEvent(new AfterLoadEvent<Person>(new Document(), Person.class, "collection-1"));
assertThat(personListener.invokedOnAfterLoad, is(true));
assertThat(contactListener.invokedOnAfterLoad, is(true));
assertThat(personListener.invokedOnAfterLoad).isTrue();
assertThat(contactListener.invokedOnAfterLoad).isTrue();
}
@Test // DATAMONGO-289
@@ -102,8 +102,8 @@ public class AbstractMongoEventListenerUnitTests {
personListener.onApplicationEvent(new AfterLoadEvent<Contact>(new Document(), Contact.class, "collection-1"));
contactListener.onApplicationEvent(new AfterLoadEvent<Contact>(new Document(), Contact.class, "collection-1"));
assertThat(personListener.invokedOnAfterLoad, is(false));
assertThat(contactListener.invokedOnAfterLoad, is(true));
assertThat(personListener.invokedOnAfterLoad).isFalse();
assertThat(contactListener.invokedOnAfterLoad).isTrue();
}
@Test // DATAMONGO-333
@@ -121,7 +121,7 @@ public class AbstractMongoEventListenerUnitTests {
SampleContactEventListener listener = new SampleContactEventListener();
listener.onApplicationEvent(event);
assertThat(listener.invokedOnBeforeDelete, is(true));
assertThat(listener.invokedOnBeforeDelete).isTrue();
}
@Test // DATAMONGO-545
@@ -131,7 +131,7 @@ public class AbstractMongoEventListenerUnitTests {
SamplePersonEventListener listener = new SamplePersonEventListener();
listener.onApplicationEvent(event);
assertThat(listener.invokedOnBeforeDelete, is(true));
assertThat(listener.invokedOnBeforeDelete).isTrue();
}
@Test // DATAMONGO-545
@@ -141,7 +141,7 @@ public class AbstractMongoEventListenerUnitTests {
SamplePersonEventListener listener = new SamplePersonEventListener();
listener.onApplicationEvent(event);
assertThat(listener.invokedOnBeforeDelete, is(false));
assertThat(listener.invokedOnBeforeDelete).isFalse();
}
@Test // DATAMONGO-545
@@ -151,7 +151,7 @@ public class AbstractMongoEventListenerUnitTests {
SamplePersonEventListener listener = new SamplePersonEventListener();
listener.onApplicationEvent(event);
assertThat(listener.invokedOnBeforeDelete, is(false));
assertThat(listener.invokedOnBeforeDelete).isFalse();
}
class SamplePersonEventListener extends AbstractMongoEventListener<Person> {

View File

@@ -30,10 +30,10 @@ import java.util.Map;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.annotation.Id;
@@ -132,8 +132,8 @@ public class ApplicationContextEventTests {
assertThat(listener.onBeforeSaveEvents.get(0).getCollectionName()).isEqualTo(COLLECTION_NAME);
assertThat(listener.onAfterSaveEvents.get(0).getCollectionName()).isEqualTo(COLLECTION_NAME);
Assert.assertTrue(personBeforeSaveListener.seenEvents.get(0) instanceof BeforeSaveEvent<?>);
Assert.assertTrue(afterSaveListener.seenEvents.get(0) instanceof AfterSaveEvent<?>);
assertThat(personBeforeSaveListener.seenEvents.get(0) instanceof BeforeSaveEvent<?>).isTrue();
assertThat(afterSaveListener.seenEvents.get(0) instanceof AfterSaveEvent<?>).isTrue();
BeforeSaveEvent<PersonPojoStringId> beforeSaveEvent = (BeforeSaveEvent<PersonPojoStringId>) personBeforeSaveListener.seenEvents
.get(0);
@@ -143,7 +143,7 @@ public class ApplicationContextEventTests {
comparePersonAndDocument(p, p2, document);
AfterSaveEvent<Object> afterSaveEvent = (AfterSaveEvent<Object>) afterSaveListener.seenEvents.get(0);
Assert.assertTrue(afterSaveEvent.getSource() instanceof PersonPojoStringId);
assertThat(afterSaveEvent.getSource() instanceof PersonPojoStringId).isTrue();
p2 = (PersonPojoStringId) afterSaveEvent.getSource();
document = beforeSaveEvent.getDocument();

View File

@@ -15,11 +15,8 @@
*/
package org.springframework.data.mongodb.core.mapping.event;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import lombok.AllArgsConstructor;
@@ -98,8 +95,8 @@ public class AuditingEntityCallbackUnitTests {
@Test // DATAMONGO-2261
public void hasExplicitOrder() {
assertThat(callback, is(instanceOf(Ordered.class)));
assertThat(callback.getOrder(), is(100));
assertThat(callback).isInstanceOf(Ordered.class);
assertThat(callback.getOrder()).isEqualTo(100);
}
@Test // DATAMONGO-2261

View File

@@ -15,11 +15,8 @@
*/
package org.springframework.data.mongodb.core.mapping.event;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import lombok.AllArgsConstructor;
@@ -35,6 +32,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.AdditionalAnswers;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.Ordered;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.Id;
@@ -98,8 +96,8 @@ public class AuditingEventListenerUnitTests {
@Test
public void hasExplicitOrder() {
assertThat(listener, is(instanceOf(Ordered.class)));
assertThat(listener.getOrder(), is(100));
assertThat(listener).isInstanceOf(Ordered.class);
assertThat(listener.getOrder()).isEqualTo(100);
}
@Test // DATAMONGO-1992

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core.mapping.event;
import static org.hamcrest.core.StringStartsWith.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
@@ -78,7 +77,7 @@ public class LoggingEventListenerTests {
listener.onAfterConvert(new AfterConvertEvent<Object>(new Document("foo", new Foo()), this, "collection"));
assertThat(appender.list.get(0).getFormattedMessage(), startsWith("onAfterConvert: { \"foo\""));
assertThat(appender.list.get(0).getFormattedMessage()).startsWith("onAfterConvert: { \"foo\"");
}
@Test // DATAMONGO-1645
@@ -86,8 +85,8 @@ public class LoggingEventListenerTests {
listener.onBeforeSave(new BeforeSaveEvent<Object>(new Foo(), new Document("foo", new Foo()), "collection"));
assertThat(appender.list.get(0).getFormattedMessage(),
startsWith("onBeforeSave: org.springframework.data.mongodb.core."));
assertThat(appender.list.get(0).getFormattedMessage())
.startsWith("onBeforeSave: org.springframework.data.mongodb.core.");
}
@Test // DATAMONGO-1645
@@ -95,8 +94,8 @@ public class LoggingEventListenerTests {
listener.onAfterSave(new AfterSaveEvent<Object>(new Foo(), new Document("foo", new Foo()), "collection"));
assertThat(appender.list.get(0).getFormattedMessage(),
startsWith("onAfterSave: org.springframework.data.mongodb.core."));
assertThat(appender.list.get(0).getFormattedMessage())
.startsWith("onAfterSave: org.springframework.data.mongodb.core.");
}
@Test // DATAMONGO-1645
@@ -104,7 +103,7 @@ public class LoggingEventListenerTests {
listener.onBeforeDelete(new BeforeDeleteEvent<Object>(new Document("foo", new Foo()), Object.class, "collection"));
assertThat(appender.list.get(0).getFormattedMessage(), startsWith("onBeforeDelete: { \"foo\""));
assertThat(appender.list.get(0).getFormattedMessage()).startsWith("onBeforeDelete: { \"foo\"");
}
@Test // DATAMONGO-1645
@@ -112,7 +111,7 @@ public class LoggingEventListenerTests {
listener.onAfterDelete(new AfterDeleteEvent<Object>(new Document("foo", new Foo()), Object.class, "collection"));
assertThat(appender.list.get(0).getFormattedMessage(), startsWith("onAfterDelete: { \"foo\""));
assertThat(appender.list.get(0).getFormattedMessage()).startsWith("onAfterDelete: { \"foo\"");
}
static class Foo {

View File

@@ -15,14 +15,14 @@
*/
package org.springframework.data.mongodb.core.mapping.event;
import static org.hamcrest.core.IsEqual.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import javax.validation.ConstraintViolationException;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.test.util.MongoVersionRule;
@@ -50,12 +50,10 @@ public class ValidatingMongoEventListenerTests {
User user = new User("john", 17);
try {
mongoTemplate.save(user);
fail();
} catch (ConstraintViolationException e) {
assertThat(e.getConstraintViolations().size(), equalTo(2));
}
assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> mongoTemplate.save(user))
.satisfies(e -> {
assertThat(e.getConstraintViolations()).hasSize(2);
});
}
@Test

View File

@@ -15,18 +15,18 @@
*/
package org.springframework.data.mongodb.core.mapreduce;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.data.Offset.offset;
import static org.springframework.data.mongodb.core.mapreduce.GroupBy.*;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import org.bson.Document;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.test.util.MongoVersionRule;
@@ -71,7 +71,7 @@ public class GroupByTests {
Document gc = new GroupBy("a").getGroupByObject();
assertThat(gc, is(Document.parse("{ \"key\" : { \"a\" : 1} , \"$reduce\" : null , \"initial\" : null }")));
assertThat(gc).isEqualTo(Document.parse("{ \"key\" : { \"a\" : 1} , \"$reduce\" : null , \"initial\" : null }"));
}
@Test
@@ -79,8 +79,8 @@ public class GroupByTests {
Document gc = GroupBy.key("a", "b").getGroupByObject();
assertThat(gc,
is(Document.parse("{ \"key\" : { \"a\" : 1 , \"b\" : 1} , \"$reduce\" : null , \"initial\" : null }")));
assertThat(gc).isEqualTo(
Document.parse("{ \"key\" : { \"a\" : 1 , \"b\" : 1} , \"$reduce\" : null , \"initial\" : null }"));
}
@Test
@@ -88,8 +88,8 @@ public class GroupByTests {
Document gc = GroupBy.keyFunction("classpath:keyFunction.js").getGroupByObject();
assertThat(gc, is(
Document.parse("{ \"$keyf\" : \"classpath:keyFunction.js\" , \"$reduce\" : null , \"initial\" : null }")));
assertThat(gc).isEqualTo(
Document.parse("{ \"$keyf\" : \"classpath:keyFunction.js\" , \"$reduce\" : null , \"initial\" : null }"));
}
@Test
@@ -145,19 +145,19 @@ public class GroupByTests {
int numResults = 0;
for (XObject xObject : results) {
if (xObject.getX() == 1) {
Assert.assertEquals(2, xObject.getCount(), 0.001);
assertThat(xObject.getCount()).isCloseTo(2, offset(0.001f));
}
if (xObject.getX() == 2) {
Assert.assertEquals(1, xObject.getCount(), 0.001);
assertThat(xObject.getCount()).isCloseTo(1, offset(0.001f));
}
if (xObject.getX() == 3) {
Assert.assertEquals(3, xObject.getCount(), 0.001);
assertThat(xObject.getCount()).isCloseTo(3, offset(0.001f));
}
numResults++;
}
assertThat(numResults, is(3));
assertThat(results.getKeys(), is(3));
assertEquals(6, results.getCount(), 0.001);
assertThat(numResults).isEqualTo(3);
assertThat(results.getKeys()).isEqualTo(3);
assertThat(results.getCount()).isCloseTo(6, offset(0.001));
}
private void createGroupByData() {

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core.mapreduce;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
@@ -33,9 +32,9 @@ public class MapReduceCountsUnitTests {
MapReduceCounts left = new MapReduceCounts(1L, 1L, 1L);
MapReduceCounts right = new MapReduceCounts(1L, 1L, 1L);
assertThat(left, is(right));
assertThat(right, is(left));
assertThat(left.hashCode(), is(right.hashCode()));
assertThat(left).isEqualTo(right);
assertThat(right).isEqualTo(left);
assertThat(left.hashCode()).isEqualTo(right.hashCode());
}
@Test // DATACMNS-378
@@ -44,8 +43,8 @@ public class MapReduceCountsUnitTests {
MapReduceCounts left = new MapReduceCounts(1L, 1L, 1L);
MapReduceCounts right = new MapReduceCounts(1L, 2L, 1L);
assertThat(left, is(not(right)));
assertThat(right, is(not(left)));
assertThat(left.hashCode(), is(not(right.hashCode())));
assertThat(left).isNotEqualTo(right);
assertThat(right).isNotEqualTo(left);
assertThat(left.hashCode()).isNotEqualTo(right.hashCode());
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core.mapreduce;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.test.util.IsBsonObject.*;
import static org.springframework.data.mongodb.test.util.Assertions.*;
import org.junit.Test;
@@ -38,11 +37,11 @@ public class MapReduceOptionsTests {
MapReduceOptions options = new MapReduceOptions();
options.limit(10);
assertThat(options.getOptionsObject(), isBsonObject().containing("limit", 10));
assertThat(options.getOptionsObject()).containsEntry("limit", 10);
}
@Test // DATAMONGO-1334
public void limitShouldNotBePresentInDocumentWhenNotSet() {
assertThat(new MapReduceOptions().getOptionsObject(), isBsonObject().notContaining("limit"));
assertThat(new MapReduceOptions().getOptionsObject()).doesNotContainKey("limit");
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core.mapreduce;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Collections;
@@ -36,7 +35,7 @@ public class MapReduceResultsUnitTests {
Document rawResult = new Document("result", "FOO");
MapReduceResults<Object> results = new MapReduceResults<Object>(Collections.emptyList(), rawResult);
assertThat(results.getOutputCollection(), is("FOO"));
assertThat(results.getOutputCollection()).isEqualTo("FOO");
}
@Test // DATAMONGO-428
@@ -45,7 +44,7 @@ public class MapReduceResultsUnitTests {
Document rawResult = new Document("result", new Document("collection", "FOO"));
MapReduceResults<Object> results = new MapReduceResults<Object>(Collections.emptyList(), rawResult);
assertThat(results.getOutputCollection(), is("FOO"));
assertThat(results.getOutputCollection()).isEqualTo("FOO");
}
@Test // DATAMONGO-378

View File

@@ -15,16 +15,15 @@
*/
package org.springframework.data.mongodb.core.query;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.test.util.IsBsonObject.*;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
@@ -41,7 +40,7 @@ public class BasicQueryUnitTests {
public void createsQueryFromPlainJson() {
Query q = new BasicQuery("{ \"name\" : \"Thomas\"}");
Document reference = new Document("name", "Thomas");
assertThat(q.getQueryObject(), is(reference));
assertThat(q.getQueryObject()).isEqualTo(reference);
}
@Test
@@ -49,7 +48,7 @@ public class BasicQueryUnitTests {
Query q = new BasicQuery("{ \"name\" : \"Thomas\"}").addCriteria(where("age").lt(80));
Document reference = new Document("name", "Thomas");
reference.put("age", new Document("$lt", 80));
assertThat(q.getQueryObject(), is(reference));
assertThat(q.getQueryObject()).isEqualTo(reference);
}
@Test
@@ -61,7 +60,7 @@ public class BasicQueryUnitTests {
Document sortReference = new Document("name", -1);
sortReference.put("lastname", 1);
assertThat(query.getSortObject(), is(sortReference));
assertThat(query.getSortObject()).isEqualTo(sortReference);
}
@Test // DATAMONGO-1093
@@ -91,9 +90,9 @@ public class BasicQueryUnitTests {
BasicQuery query2 = new BasicQuery(qry, fields);
query2.setSortObject(new Document("name", -1));
assertThat(query1, is(equalTo(query1)));
assertThat(query1, is(equalTo(query2)));
assertThat(query1.hashCode(), is(query2.hashCode()));
assertThat(query1).isEqualTo(query1);
assertThat(query1).isEqualTo(query2);
assertThat(query1.hashCode()).isEqualTo(query2.hashCode());
}
@Test // DATAMONGO-1093
@@ -108,8 +107,8 @@ public class BasicQueryUnitTests {
BasicQuery query2 = new BasicQuery(qry, fields);
query2.setSortObject(new Document("name", 1));
assertThat(query1, is(not(equalTo(query2))));
assertThat(query1.hashCode(), is(not(query2.hashCode())));
assertThat(query1).isNotEqualTo(query2);
assertThat(query1.hashCode()).isNotEqualTo(query2.hashCode());
}
@Test // DATAMONGO-1093
@@ -124,8 +123,8 @@ public class BasicQueryUnitTests {
BasicQuery query2 = new BasicQuery(qry, fields);
query2.getMeta().setComment("bar");
assertThat(query1, is(not(equalTo(query2))));
assertThat(query1.hashCode(), is(not(query2.hashCode())));
assertThat(query1).isNotEqualTo(query2);
assertThat(query1.hashCode()).isNotEqualTo(query2.hashCode());
}
@Test // DATAMONGO-1387
@@ -136,7 +135,7 @@ public class BasicQueryUnitTests {
BasicQuery query1 = new BasicQuery(qry, fields);
assertThat(query1.getFieldsObject(), isBsonObject().containing("name").containing("age"));
assertThat(query1.getFieldsObject()).containsKeys("name", "age");
}
@Test // DATAMONGO-1387
@@ -147,7 +146,7 @@ public class BasicQueryUnitTests {
BasicQuery query1 = new BasicQuery(qry);
query1.fields().include("name");
assertThat(query1.getFieldsObject(), isBsonObject().containing("name"));
assertThat(query1.getFieldsObject()).containsKey("name");
}
@Test // DATAMONGO-1387
@@ -159,6 +158,6 @@ public class BasicQueryUnitTests {
BasicQuery query1 = new BasicQuery(qry, fields);
query1.fields().include("gender");
assertThat(query1.getFieldsObject(), isBsonObject().containing("name").containing("age").containing("gender"));
assertThat(query1.getFieldsObject()).containsKeys("name", "age", "gender");
}
}

View File

@@ -15,18 +15,14 @@
*/
package org.springframework.data.mongodb.core.query;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.*;
import static org.junit.Assert.assertThat;
import static org.springframework.data.mongodb.test.util.IsBsonObject.*;
import static org.springframework.data.mongodb.test.util.Assertions.*;
import java.util.Arrays;
import java.util.Collections;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.InvalidMongoDbApiUsageException;
import org.springframework.data.mongodb.core.geo.GeoJsonLineString;
@@ -44,13 +40,13 @@ public class CriteriaUnitTests {
@Test
public void testSimpleCriteria() {
Criteria c = new Criteria("name").is("Bubba");
assertEquals(Document.parse("{ \"name\" : \"Bubba\"}"), c.getCriteriaObject());
assertThat(c.getCriteriaObject()).isEqualTo(Document.parse("{ \"name\" : \"Bubba\"}"));
}
@Test
public void testNotEqualCriteria() {
Criteria c = new Criteria("name").ne("Bubba");
assertEquals(Document.parse("{ \"name\" : { \"$ne\" : \"Bubba\"}}"), c.getCriteriaObject());
assertThat(c.getCriteriaObject()).isEqualTo(Document.parse("{ \"name\" : { \"$ne\" : \"Bubba\"}}"));
}
@Test
@@ -59,13 +55,13 @@ public class CriteriaUnitTests {
Document reference = new Document("name", null);
Criteria criteria = new Criteria("name").is(null);
assertThat(criteria.getCriteriaObject(), is(reference));
assertThat(criteria.getCriteriaObject()).isEqualTo(reference);
}
@Test
public void testChainedCriteria() {
Criteria c = new Criteria("name").is("Bubba").and("age").lt(21);
assertEquals(Document.parse("{ \"name\" : \"Bubba\" , \"age\" : { \"$lt\" : 21}}"), c.getCriteriaObject());
assertThat(c.getCriteriaObject()).isEqualTo(Document.parse("{ \"name\" : \"Bubba\" , \"age\" : { \"$lt\" : 21}}"));
}
@Test(expected = InvalidMongoDbApiUsageException.class)
@@ -80,8 +76,8 @@ public class CriteriaUnitTests {
Criteria left = new Criteria("name").is("Foo").and("lastname").is("Bar");
Criteria right = new Criteria("name").is("Bar").and("lastname").is("Bar");
assertThat(left, is(not(right)));
assertThat(right, is(not(left)));
assertThat(left).isNotEqualTo(right);
assertThat(right).isNotEqualTo(left);
}
@Test(expected = IllegalArgumentException.class) // DATAMONGO-507
@@ -114,8 +110,8 @@ public class CriteriaUnitTests {
Criteria c = Criteria.where("age").not().gt(18).and("status").is("student");
Document co = c.getCriteriaObject();
assertThat(co, is(notNullValue()));
assertThat(co, is(Document.parse("{ \"age\" : { \"$not\" : { \"$gt\" : 18}} , \"status\" : \"student\"}")));
assertThat(co).isNotNull();
assertThat(co).isEqualTo(Document.parse("{ \"age\" : { \"$not\" : { \"$gt\" : 18}} , \"status\" : \"student\"}"));
}
@Test // DATAMONGO-1068
@@ -123,7 +119,7 @@ public class CriteriaUnitTests {
Document document = new Criteria().getCriteriaObject();
assertThat(document, equalTo(new Document()));
assertThat(document).isEqualTo(new Document());
}
@Test // DATAMONGO-1068
@@ -131,7 +127,7 @@ public class CriteriaUnitTests {
Document document = new Criteria().lt("foo").getCriteriaObject();
assertThat(document, equalTo(new Document().append("$lt", "foo")));
assertThat(document).isEqualTo(new Document().append("$lt", "foo"));
}
@Test // DATAMONGO-1068
@@ -139,7 +135,7 @@ public class CriteriaUnitTests {
Document document = new Criteria().lt("foo").gt("bar").getCriteriaObject();
assertThat(document, equalTo(new Document().append("$lt", "foo").append("$gt", "bar")));
assertThat(document).isEqualTo(new Document().append("$lt", "foo").append("$gt", "bar"));
}
@Test // DATAMONGO-1068
@@ -147,7 +143,7 @@ public class CriteriaUnitTests {
Document document = new Criteria().lt("foo").not().getCriteriaObject();
assertThat(document, equalTo(new Document().append("$not", new Document("$lt", "foo"))));
assertThat(document).isEqualTo(new Document().append("$not", new Document("$lt", "foo")));
}
@Test // DATAMONGO-1135
@@ -155,7 +151,7 @@ public class CriteriaUnitTests {
Document document = new Criteria("foo").near(new GeoJsonPoint(100, 200)).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$near.$geometry", new GeoJsonPoint(100, 200)));
assertThat(document).containsEntry("foo.$near.$geometry", new GeoJsonPoint(100, 200));
}
@Test // DATAMONGO-1135
@@ -163,7 +159,7 @@ public class CriteriaUnitTests {
Document document = new Criteria("foo").near(new Point(100, 200)).getCriteriaObject();
assertThat(document, isBsonObject().notContaining("foo.$near.$geometry"));
assertThat(document).doesNotContainKey("foo.$near.$geometry");
}
@Test // DATAMONGO-1135
@@ -171,7 +167,7 @@ public class CriteriaUnitTests {
Document document = new Criteria("foo").near(new GeoJsonPoint(100, 200)).maxDistance(50D).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$near.$maxDistance", 50D));
assertThat(document).containsEntry("foo.$near.$maxDistance", 50D);
}
@Test // DATAMONGO-1135
@@ -179,7 +175,7 @@ public class CriteriaUnitTests {
Document document = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).maxDistance(50D).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$nearSphere.$maxDistance", 50D));
assertThat(document).containsEntry("foo.$nearSphere.$maxDistance", 50D);
}
@Test // DATAMONGO-1110
@@ -187,7 +183,7 @@ public class CriteriaUnitTests {
Document document = new Criteria("foo").near(new GeoJsonPoint(100, 200)).minDistance(50D).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$near.$minDistance", 50D));
assertThat(document).containsEntry("foo.$near.$minDistance", 50D);
}
@Test // DATAMONGO-1110
@@ -195,7 +191,7 @@ public class CriteriaUnitTests {
Document document = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).minDistance(50D).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$nearSphere.$minDistance", 50D));
assertThat(document).containsEntry("foo.$nearSphere.$minDistance", 50D);
}
@Test // DATAMONGO-1110
@@ -204,8 +200,8 @@ public class CriteriaUnitTests {
Document document = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).minDistance(50D).maxDistance(100D)
.getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$nearSphere.$minDistance", 50D));
assertThat(document, isBsonObject().containing("foo.$nearSphere.$maxDistance", 100D));
assertThat(document).containsEntry("foo.$nearSphere.$minDistance", 50D);
assertThat(document).containsEntry("foo.$nearSphere.$maxDistance", 100D);
}
@Test(expected = IllegalArgumentException.class) // DATAMONGO-1134
@@ -219,7 +215,7 @@ public class CriteriaUnitTests {
GeoJsonLineString lineString = new GeoJsonLineString(new Point(0, 0), new Point(10, 10));
Document document = new Criteria("foo").intersects(lineString).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$geoIntersects.$geometry", lineString));
assertThat(document).containsEntry("foo.$geoIntersects.$geometry", lineString);
}
@Test // DATAMONGO-1835
@@ -228,8 +224,8 @@ public class CriteriaUnitTests {
MongoJsonSchema schema = MongoJsonSchema.builder().required("name").build();
Criteria criteria = Criteria.where("foo").is("bar").andDocumentStructureMatches(schema);
assertThat(criteria.getCriteriaObject(), is(equalTo(new Document("foo", "bar").append("$jsonSchema",
new Document("type", "object").append("required", Collections.singletonList("name"))))));
assertThat(criteria.getCriteriaObject()).isEqualTo(new Document("foo", "bar").append("$jsonSchema",
new Document("type", "object").append("required", Collections.singletonList("name"))));
}
@Test // DATAMONGO-1835
@@ -238,8 +234,8 @@ public class CriteriaUnitTests {
MongoJsonSchema schema = MongoJsonSchema.builder().required("name").build();
Criteria criteria = Criteria.matchingDocumentStructure(schema);
assertThat(criteria.getCriteriaObject(), is(equalTo(new Document("$jsonSchema",
new Document("type", "object").append("required", Collections.singletonList("name"))))));
assertThat(criteria.getCriteriaObject()).isEqualTo(new Document("$jsonSchema",
new Document("type", "object").append("required", Collections.singletonList("name"))));
}
@Test // DATAMONGO-1808
@@ -247,8 +243,8 @@ public class CriteriaUnitTests {
Criteria numericBitmaskCriteria = new Criteria("field").bits().allClear(0b101);
assertThat(numericBitmaskCriteria.getCriteriaObject(),
is(equalTo(Document.parse("{ \"field\" : { \"$bitsAllClear\" : 5} }"))));
assertThat(numericBitmaskCriteria.getCriteriaObject())
.isEqualTo(Document.parse("{ \"field\" : { \"$bitsAllClear\" : 5} }"));
}
@Test // DATAMONGO-1808
@@ -256,8 +252,8 @@ public class CriteriaUnitTests {
Criteria bitPositionsBitmaskCriteria = new Criteria("field").bits().allClear(Arrays.asList(0, 2));
assertThat(bitPositionsBitmaskCriteria.getCriteriaObject(),
is(equalTo(Document.parse("{ \"field\" : { \"$bitsAllClear\" : [ 0, 2 ]} }"))));
assertThat(bitPositionsBitmaskCriteria.getCriteriaObject())
.isEqualTo(Document.parse("{ \"field\" : { \"$bitsAllClear\" : [ 0, 2 ]} }"));
}
@Test // DATAMONGO-1808
@@ -265,8 +261,8 @@ public class CriteriaUnitTests {
Criteria numericBitmaskCriteria = new Criteria("field").bits().allSet(0b101);
assertThat(numericBitmaskCriteria.getCriteriaObject(),
is(equalTo(Document.parse("{ \"field\" : { \"$bitsAllSet\" : 5} }"))));
assertThat(numericBitmaskCriteria.getCriteriaObject())
.isEqualTo(Document.parse("{ \"field\" : { \"$bitsAllSet\" : 5} }"));
}
@Test // DATAMONGO-1808
@@ -274,8 +270,8 @@ public class CriteriaUnitTests {
Criteria bitPositionsBitmaskCriteria = new Criteria("field").bits().allSet(Arrays.asList(0, 2));
assertThat(bitPositionsBitmaskCriteria.getCriteriaObject(),
is(equalTo(Document.parse("{ \"field\" : { \"$bitsAllSet\" : [ 0, 2 ]} }"))));
assertThat(bitPositionsBitmaskCriteria.getCriteriaObject())
.isEqualTo(Document.parse("{ \"field\" : { \"$bitsAllSet\" : [ 0, 2 ]} }"));
}
@Test // DATAMONGO-1808
@@ -283,8 +279,8 @@ public class CriteriaUnitTests {
Criteria numericBitmaskCriteria = new Criteria("field").bits().anyClear(0b101);
assertThat(numericBitmaskCriteria.getCriteriaObject(),
is(equalTo(Document.parse("{ \"field\" : { \"$bitsAnyClear\" : 5} }"))));
assertThat(numericBitmaskCriteria.getCriteriaObject())
.isEqualTo(Document.parse("{ \"field\" : { \"$bitsAnyClear\" : 5} }"));
}
@Test // DATAMONGO-1808
@@ -292,8 +288,8 @@ public class CriteriaUnitTests {
Criteria bitPositionsBitmaskCriteria = new Criteria("field").bits().anyClear(Arrays.asList(0, 2));
assertThat(bitPositionsBitmaskCriteria.getCriteriaObject(),
is(equalTo(Document.parse("{ \"field\" : { \"$bitsAnyClear\" : [ 0, 2 ]} }"))));
assertThat(bitPositionsBitmaskCriteria.getCriteriaObject())
.isEqualTo(Document.parse("{ \"field\" : { \"$bitsAnyClear\" : [ 0, 2 ]} }"));
}
@Test // DATAMONGO-1808
@@ -301,8 +297,8 @@ public class CriteriaUnitTests {
Criteria numericBitmaskCriteria = new Criteria("field").bits().anySet(0b101);
assertThat(numericBitmaskCriteria.getCriteriaObject(),
is(equalTo(Document.parse("{ \"field\" : { \"$bitsAnySet\" : 5} }"))));
assertThat(numericBitmaskCriteria.getCriteriaObject())
.isEqualTo(Document.parse("{ \"field\" : { \"$bitsAnySet\" : 5} }"));
}
@Test // DATAMONGO-1808
@@ -310,8 +306,8 @@ public class CriteriaUnitTests {
Criteria bitPositionsBitmaskCriteria = new Criteria("field").bits().anySet(Arrays.asList(0, 2));
assertThat(bitPositionsBitmaskCriteria.getCriteriaObject(),
is(equalTo(Document.parse("{ \"field\" : { \"$bitsAnySet\" : [ 0, 2 ]} }"))));
assertThat(bitPositionsBitmaskCriteria.getCriteriaObject())
.isEqualTo(Document.parse("{ \"field\" : { \"$bitsAnySet\" : [ 0, 2 ]} }"));
}
@Test // DATAMONGO-2002

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core.query;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
@@ -33,8 +32,8 @@ public class FieldUnitTests {
Field left = new Field().elemMatch("key", Criteria.where("foo").is("bar"));
Field right = new Field().elemMatch("key", Criteria.where("foo").is("bar"));
assertThat(left, is(right));
assertThat(right, is(left));
assertThat(left).isEqualTo(right);
assertThat(right).isEqualTo(left);
}
@Test
@@ -43,7 +42,7 @@ public class FieldUnitTests {
Field left = new Field().elemMatch("key", Criteria.where("foo").is("bar"));
Field right = new Field().elemMatch("key", Criteria.where("foo").is("foo"));
assertThat(left, is(not(right)));
assertThat(right, is(not(left)));
assertThat(left).isNotEqualTo(right);
assertThat(right).isNotEqualTo(left);
}
}

View File

@@ -15,11 +15,11 @@
*/
package org.springframework.data.mongodb.core.query;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;
import org.springframework.data.mongodb.core.index.GeospatialIndex;
@@ -36,44 +36,44 @@ public class IndexUnitTests {
@Test
public void testWithAscendingIndex() {
Index i = new Index().on("name", Direction.ASC);
assertEquals(Document.parse("{ \"name\" : 1}"), i.getIndexKeys());
assertThat(i.getIndexKeys()).isEqualTo(Document.parse("{ \"name\" : 1}"));
}
@Test
public void testWithDescendingIndex() {
Index i = new Index().on("name", Direction.DESC);
assertEquals(Document.parse("{ \"name\" : -1}"), i.getIndexKeys());
assertThat(i.getIndexKeys()).isEqualTo(Document.parse("{ \"name\" : -1}"));
}
@Test
public void testNamedMultiFieldUniqueIndex() {
Index i = new Index().on("name", Direction.ASC).on("age", Direction.DESC);
i.named("test").unique();
assertEquals(Document.parse("{ \"name\" : 1 , \"age\" : -1}"), i.getIndexKeys());
assertEquals(Document.parse("{ \"name\" : \"test\" , \"unique\" : true}"), i.getIndexOptions());
assertThat(i.getIndexKeys()).isEqualTo(Document.parse("{ \"name\" : 1 , \"age\" : -1}"));
assertThat(i.getIndexOptions()).isEqualTo(Document.parse("{ \"name\" : \"test\" , \"unique\" : true}"));
}
@Test
public void testWithSparse() {
Index i = new Index().on("name", Direction.ASC);
i.sparse().unique();
assertEquals(Document.parse("{ \"name\" : 1}"), i.getIndexKeys());
assertEquals(Document.parse("{ \"unique\" : true , \"sparse\" : true}"), i.getIndexOptions());
assertThat(i.getIndexKeys()).isEqualTo(Document.parse("{ \"name\" : 1}"));
assertThat(i.getIndexOptions()).isEqualTo(Document.parse("{ \"unique\" : true , \"sparse\" : true}"));
}
@Test
public void testGeospatialIndex() {
GeospatialIndex i = new GeospatialIndex("location").withMin(0);
assertEquals(Document.parse("{ \"location\" : \"2d\"}"), i.getIndexKeys());
assertEquals(Document.parse("{ \"min\" : 0}"), i.getIndexOptions());
assertThat(i.getIndexKeys()).isEqualTo(Document.parse("{ \"location\" : \"2d\"}"));
assertThat(i.getIndexOptions()).isEqualTo(Document.parse("{ \"min\" : 0}"));
}
@Test // DATAMONGO-778
public void testGeospatialIndex2DSphere() {
GeospatialIndex i = new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2DSPHERE);
assertEquals(Document.parse("{ \"location\" : \"2dsphere\"}"), i.getIndexKeys());
assertEquals(Document.parse("{ }"), i.getIndexOptions());
assertThat(i.getIndexKeys()).isEqualTo(Document.parse("{ \"location\" : \"2dsphere\"}"));
assertThat(i.getIndexOptions()).isEqualTo(Document.parse("{ }"));
}
@Test // DATAMONGO-778
@@ -81,14 +81,14 @@ public class IndexUnitTests {
GeospatialIndex i = new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_HAYSTACK)
.withAdditionalField("name").withBucketSize(40);
assertEquals(Document.parse("{ \"location\" : \"geoHaystack\" , \"name\" : 1}"), i.getIndexKeys());
assertEquals(Document.parse("{ \"bucketSize\" : 40.0}"), i.getIndexOptions());
assertThat(i.getIndexKeys()).isEqualTo(Document.parse("{ \"location\" : \"geoHaystack\" , \"name\" : 1}"));
assertThat(i.getIndexOptions()).isEqualTo(Document.parse("{ \"bucketSize\" : 40.0}"));
}
@Test
public void ensuresPropertyOrder() {
Index on = new Index("foo", Direction.ASC).on("bar", Direction.ASC);
assertThat(on.getIndexKeys(), is(Document.parse("{ \"foo\" : 1 , \"bar\" : 1}")));
assertThat(on.getIndexKeys()).isEqualTo(Document.parse("{ \"foo\" : 1 , \"bar\" : 1}"));
}
}

View File

@@ -1,151 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.query;
import org.bson.Document;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import org.hamcrest.core.IsEqual;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.util.StringUtils;
/**
* A {@link TypeSafeMatcher} that tests whether a given {@link Query} matches a query specification.
*
* @author Christoph Strobl
* @author Mark Paluch
* @param <T>
*/
public class IsQuery<T extends Query> extends TypeSafeMatcher<T> {
protected Document query;
protected Document sort;
protected Document fields;
private long skip;
private int limit;
private String hint;
protected IsQuery() {
query = new Document();
sort = new Document();
fields = new Document();
}
public static <T extends BasicQuery> IsQuery<T> isQuery() {
return new IsQuery<T>();
}
public IsQuery<T> limitingTo(int limit) {
this.limit = limit;
return this;
}
public IsQuery<T> skippig(long skip) {
this.skip = skip;
return this;
}
public IsQuery<T> providingHint(String hint) {
this.hint = hint;
return this;
}
public IsQuery<T> includingField(String fieldname) {
if (fields == null) {
fields = new Document();
}
fields.put(fieldname, 1);
return this;
}
public IsQuery<T> excludingField(String fieldname) {
if (fields == null) {
fields = new Document();
}
fields.put(fieldname, -1);
return this;
}
public IsQuery<T> sortingBy(String fieldname, Direction direction) {
sort.put(fieldname, Direction.ASC.equals(direction) ? 1 : -1);
return this;
}
public IsQuery<T> where(Criteria criteria) {
this.query.putAll(criteria.getCriteriaObject());
return this;
}
@Override
public void describeTo(Description description) {
BasicQuery expected = new BasicQuery(this.query, this.fields);
expected.setSortObject(sort);
expected.skip(this.skip);
expected.limit(this.limit);
if (StringUtils.hasText(this.hint)) {
expected.withHint(this.hint);
}
description.appendValue(expected);
}
@Override
protected boolean matchesSafely(T item) {
if (item == null) {
return false;
}
if (!new IsEqual<Document>(query).matches(item.getQueryObject())) {
return false;
}
if ((item.getSortObject() == null || item.getSortObject().isEmpty()) && !sort.isEmpty()) {
if (!new IsEqual<Document>(sort).matches(item.getSortObject())) {
return false;
}
}
if (!new IsEqual<Document>(fields).matches(item.getFieldsObject())) {
return false;
}
if (!new IsEqual<String>(this.hint).matches(item.getHint())) {
return false;
}
if (!new IsEqual(this.skip).matches(item.getSkip())) {
return false;
}
if (!new IsEqual<Integer>(this.limit).matches(item.getLimit())) {
return false;
}
return true;
}
}

View File

@@ -1,141 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.query;
import org.bson.Document;
import org.hamcrest.TypeSafeMatcher;
import org.springframework.util.StringUtils;
/**
* A {@link TypeSafeMatcher} that tests whether a given {@link TextQuery} matches a query specification.
*
* @author Christoph Strobl
* @param <T>
*/
public class IsTextQuery<T extends Query> extends IsQuery<T> {
private final String SCORE_DEFAULT_FIELDNAME = "score";
private final Document META_TEXT_SCORE = new Document("$meta", "textScore");
private String scoreFieldName = SCORE_DEFAULT_FIELDNAME;
private IsTextQuery() {
super();
}
public static <T extends Query> IsTextQuery<T> isTextQuery() {
return new IsTextQuery<T>();
}
public IsTextQuery<T> searchingFor(String term) {
appendTerm(term);
return this;
}
public IsTextQuery<T> inLanguage(String language) {
appendLanguage(language);
return this;
}
public IsTextQuery<T> returningScore() {
if (fields == null) {
fields = new Document();
}
fields.put(scoreFieldName, META_TEXT_SCORE);
return this;
}
public IsTextQuery<T> returningScoreAs(String fieldname) {
this.scoreFieldName = fieldname != null ? fieldname : SCORE_DEFAULT_FIELDNAME;
return this.returningScore();
}
public IsTextQuery<T> sortingByScore() {
sort.put(scoreFieldName, META_TEXT_SCORE);
return this;
}
@Override
public IsTextQuery<T> where(Criteria criteria) {
super.where(criteria);
return this;
}
@Override
public IsTextQuery<T> excludingField(String fieldname) {
super.excludingField(fieldname);
return this;
}
@Override
public IsTextQuery<T> includingField(String fieldname) {
super.includingField(fieldname);
return this;
}
@Override
public IsTextQuery<T> limitingTo(int limit) {
super.limitingTo(limit);
return this;
}
@Override
public IsQuery<T> skippig(long skip) {
super.skippig(skip);
return this;
}
private void appendLanguage(String language) {
Document document = getOrCreateTextDocument();
document.put("$language", language);
}
private Document getOrCreateTextDocument() {
Document document = (Document) query.get("$text");
if (document == null) {
document = new Document();
}
return document;
}
private void appendTerm(String term) {
Document document = getOrCreateTextDocument();
String searchString = (String) document.get("$search");
if (StringUtils.hasText(searchString)) {
searchString += (" " + term);
} else {
searchString = term;
}
document.put("$search", searchString);
query.put("$text", document);
}
}

View File

@@ -16,10 +16,11 @@
package org.springframework.data.mongodb.core.query;
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 org.junit.Test;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
@@ -36,7 +37,7 @@ public class MetricConversionUnitTests {
Distance distance = new Distance(1, Metrics.MILES);
double distanceInMeters = MetricConversion.getDistanceInMeters(distance);
assertThat(distanceInMeters, is(closeTo(1609.3438343d, 0.000000001)));
assertThat(distanceInMeters).isCloseTo(1609.3438343d, offset(0.000000001));
}
@Test // DATAMONGO-1348
@@ -45,7 +46,7 @@ public class MetricConversionUnitTests {
Distance distance = new Distance(1, Metrics.KILOMETERS);
double distanceInMeters = MetricConversion.getDistanceInMeters(distance);
assertThat(distanceInMeters, is(closeTo(1000, 0.000000001)));
assertThat(distanceInMeters).isCloseTo(1000, offset(0.000000001));
}
@Test // DATAMONGO-1348
@@ -53,7 +54,7 @@ public class MetricConversionUnitTests {
double multiplier = MetricConversion.getMetersToMetricMultiplier(Metrics.KILOMETERS);
assertThat(multiplier, is(closeTo(0.001, 0.000000001)));
assertThat(multiplier).isCloseTo(0.001, offset(0.000000001));
}
@Test // DATAMONGO-1348
@@ -61,7 +62,7 @@ public class MetricConversionUnitTests {
double multiplier = MetricConversion.getMetersToMetricMultiplier(Metrics.MILES);
assertThat(multiplier, is(closeTo(0.00062137, 0.000000001)));
assertThat(multiplier).isCloseTo(0.00062137, offset(0.000000001));
}
}

View File

@@ -15,14 +15,13 @@
*/
package org.springframework.data.mongodb.core.query;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.test.util.IsBsonObject.*;
import static org.springframework.data.mongodb.test.util.Assertions.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import org.junit.Test;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.geo.Distance;
@@ -54,9 +53,9 @@ public class NearQueryUnitTests {
NearQuery query = NearQuery.near(2.5, 2.5, Metrics.KILOMETERS).maxDistance(150);
assertThat(query.getMaxDistance(), is(ONE_FIFTY_KILOMETERS));
assertThat(query.getMetric(), is((Metric) Metrics.KILOMETERS));
assertThat(query.isSpherical(), is(true));
assertThat(query.getMaxDistance()).isEqualTo(ONE_FIFTY_KILOMETERS);
assertThat(query.getMetric()).isEqualTo((Metric) Metrics.KILOMETERS);
assertThat(query.isSpherical()).isTrue();
}
@Test
@@ -66,27 +65,27 @@ public class NearQueryUnitTests {
query.inMiles();
assertThat(query.getMetric(), is((Metric) Metrics.MILES));
assertThat(query.getMetric()).isEqualTo((Metric) Metrics.MILES);
}
@Test
public void configuresResultMetricCorrectly() {
NearQuery query = NearQuery.near(2.5, 2.1);
assertThat(query.getMetric(), is((Metric) Metrics.NEUTRAL));
assertThat(query.getMetric()).isEqualTo((Metric) Metrics.NEUTRAL);
query = query.maxDistance(ONE_FIFTY_KILOMETERS);
assertThat(query.getMetric(), is((Metric) Metrics.KILOMETERS));
assertThat(query.getMaxDistance(), is(ONE_FIFTY_KILOMETERS));
assertThat(query.isSpherical(), is(true));
assertThat(query.getMetric()).isEqualTo((Metric) Metrics.KILOMETERS);
assertThat(query.getMaxDistance()).isEqualTo(ONE_FIFTY_KILOMETERS);
assertThat(query.isSpherical()).isTrue();
query = query.in(Metrics.MILES);
assertThat(query.getMetric(), is((Metric) Metrics.MILES));
assertThat(query.getMaxDistance(), is(ONE_FIFTY_KILOMETERS));
assertThat(query.isSpherical(), is(true));
assertThat(query.getMetric()).isEqualTo((Metric) Metrics.MILES);
assertThat(query.getMaxDistance()).isEqualTo(ONE_FIFTY_KILOMETERS);
assertThat(query.isSpherical()).isTrue();
query = query.maxDistance(new Distance(200, Metrics.KILOMETERS));
assertThat(query.getMetric(), is((Metric) Metrics.MILES));
assertThat(query.getMetric()).isEqualTo((Metric) Metrics.MILES);
}
@Test // DATAMONGO-445, DATAMONGO-2264
@@ -95,8 +94,8 @@ public class NearQueryUnitTests {
Pageable pageable = PageRequest.of(3, 5);
NearQuery query = NearQuery.near(new Point(1, 1)).with(pageable);
assertThat(query.getSkip(), is((long) pageable.getPageNumber() * pageable.getPageSize()));
assertThat(query.toDocument().get("num"), is((long) pageable.getPageSize()));
assertThat(query.getSkip()).isEqualTo((long) pageable.getPageNumber() * pageable.getPageSize());
assertThat(query.toDocument().get("num")).isEqualTo((long) pageable.getPageSize());
}
@Test // DATAMONGO-445
@@ -107,8 +106,8 @@ public class NearQueryUnitTests {
NearQuery query = NearQuery.near(new Point(1, 1))
.query(Query.query(Criteria.where("foo").is("bar")).limit(limit).skip(skip));
assertThat(query.getSkip(), is(skip));
assertThat((Long) query.toDocument().get("num"), is((long) limit));
assertThat(query.getSkip()).isEqualTo(skip);
assertThat((Long) query.toDocument().get("num")).isEqualTo((long) limit);
}
@Test // DATAMONGO-445, DATAMONGO-2264
@@ -120,15 +119,15 @@ public class NearQueryUnitTests {
NearQuery query = NearQuery.near(new Point(1, 1))
.query(Query.query(Criteria.where("foo").is("bar")).limit(limit).skip(skip)).with(pageable);
assertThat(query.getSkip(), is((long) pageable.getPageNumber() * pageable.getPageSize()));
assertThat(query.toDocument().get("num"), is((long) pageable.getPageSize()));
assertThat(query.getSkip()).isEqualTo((long) pageable.getPageNumber() * pageable.getPageSize());
assertThat(query.toDocument().get("num")).isEqualTo((long) pageable.getPageSize());
}
@Test // DATAMONGO-829
public void nearQueryShouldInoreZeroLimitFromQuery() {
NearQuery query = NearQuery.near(new Point(1, 2)).query(Query.query(Criteria.where("foo").is("bar")));
assertThat(query.toDocument().get("num"), nullValue());
assertThat(query.toDocument().get("num")).isNull();
}
@Test(expected = IllegalArgumentException.class) // DATAMONOGO-829
@@ -144,7 +143,7 @@ public class NearQueryUnitTests {
query.num(num);
query.query(Query.query(Criteria.where("foo").is("bar")));
assertThat(DocumentTestUtils.getTypedValue(query.toDocument(), "num", Long.class), is(num));
assertThat(DocumentTestUtils.getTypedValue(query.toDocument(), "num", Long.class)).isEqualTo(num);
}
@Test // DATAMONGO-1348
@@ -152,7 +151,7 @@ public class NearQueryUnitTests {
NearQuery query = NearQuery.near(new Point(27.987901, 86.9165379));
assertThat(query.toDocument(), isBsonObject().containing("spherical", false));
assertThat(query.toDocument()).containsEntry("spherical", false);
}
@Test // DATAMONGO-1348
@@ -161,7 +160,7 @@ public class NearQueryUnitTests {
NearQuery query = NearQuery.near(new Point(27.987901, 86.9165379));
query.spherical(true);
assertThat(query.toDocument(), isBsonObject().containing("spherical", true));
assertThat(query.toDocument()).containsEntry("spherical", true);
}
@Test // DATAMONGO-1348
@@ -169,7 +168,7 @@ public class NearQueryUnitTests {
NearQuery query = NearQuery.near(new GeoJsonPoint(27.987901, 86.9165379));
assertThat(query.toDocument(), isBsonObject().containing("spherical", true));
assertThat(query.toDocument()).containsEntry("spherical", true);
}
@Test // DATAMONGO-1348
@@ -178,7 +177,7 @@ public class NearQueryUnitTests {
NearQuery query = NearQuery.near(new GeoJsonPoint(27.987901, 86.9165379));
query.spherical(false);
assertThat(query.toDocument(), isBsonObject().containing("spherical", true));
assertThat(query.toDocument()).containsEntry("spherical", true);
}
@Test // DATAMONGO-1348
@@ -190,8 +189,8 @@ public class NearQueryUnitTests {
double meterToRadianMultiplier = BigDecimal.valueOf(1 / Metrics.KILOMETERS.getMultiplier() / 1000).//
setScale(8, RoundingMode.HALF_UP).//
doubleValue();
assertThat(query.toDocument(), isBsonObject().containing("maxDistance", Metrics.KILOMETERS.getMultiplier() * 1000)
.containing("distanceMultiplier", meterToRadianMultiplier));
assertThat(query.toDocument()).containsEntry("maxDistance", Metrics.KILOMETERS.getMultiplier() * 1000)
.containsEntry("distanceMultiplier", meterToRadianMultiplier);
}
@Test // DATAMONGO-1348
@@ -200,8 +199,7 @@ public class NearQueryUnitTests {
NearQuery query = NearQuery.near(new GeoJsonPoint(27.987901, 86.9165379));
query.maxDistance(new Distance(1, Metrics.KILOMETERS));
assertThat(query.toDocument(),
isBsonObject().containing("maxDistance", 1000D).containing("distanceMultiplier", 0.001D));
assertThat(query.toDocument()).containsEntry("maxDistance", 1000D).containsEntry("distanceMultiplier", 0.001D);
}
@Test // DATAMONGO-1348
@@ -210,8 +208,8 @@ public class NearQueryUnitTests {
NearQuery query = NearQuery.near(new GeoJsonPoint(27.987901, 86.9165379));
query.maxDistance(new Distance(1, Metrics.MILES));
assertThat(query.toDocument(),
isBsonObject().containing("maxDistance", 1609.3438343D).containing("distanceMultiplier", 0.00062137D));
assertThat(query.toDocument()).containsEntry("maxDistance", 1609.3438343D).containsEntry("distanceMultiplier",
0.00062137D);
}
@Test // DATAMONGO-1348
@@ -220,8 +218,8 @@ public class NearQueryUnitTests {
NearQuery query = NearQuery.near(new GeoJsonPoint(27.987901, 86.9165379));
query.maxDistance(new Distance(1, Metrics.MILES)).in(Metrics.KILOMETERS);
assertThat(query.toDocument(),
isBsonObject().containing("maxDistance", 1609.3438343D).containing("distanceMultiplier", 0.001D));
assertThat(query.toDocument()).containsEntry("maxDistance", 1609.3438343D).containsEntry("distanceMultiplier",
0.001D);
}
@Test // DATAMONGO-1348
@@ -230,7 +228,6 @@ public class NearQueryUnitTests {
NearQuery query = NearQuery.near(new GeoJsonPoint(27.987901, 86.9165379));
query.maxDistance(new Distance(1, Metrics.KILOMETERS)).in(Metrics.MILES);
assertThat(query.toDocument(),
isBsonObject().containing("maxDistance", 1000D).containing("distanceMultiplier", 0.00062137D));
assertThat(query.toDocument()).containsEntry("maxDistance", 1000D).containsEntry("distanceMultiplier", 0.00062137D);
}
}

View File

@@ -20,8 +20,8 @@ import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.core.query.Query.*;
import org.bson.Document;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
@@ -76,7 +76,7 @@ public class QueryTests {
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}}]}");
Assert.assertEquals(expected, q.getQueryObject());
assertThat(q.getQueryObject()).isEqualTo(expected);
}
@Test
@@ -96,7 +96,7 @@ public class QueryTests {
assertThat(q.getQueryObject()).isEqualTo(Document
.parse("{ \"name\" : { \"$gte\" : \"M\" , \"$lte\" : \"T\"} , \"age\" : { \"$not\" : { \"$gt\" : 22}}}"));
Assert.assertEquals(50, q.getLimit());
assertThat(q.getLimit()).isEqualTo(50);
}
@Test

View File

@@ -15,11 +15,11 @@
*/
package org.springframework.data.mongodb.core.query;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
@@ -35,20 +35,20 @@ public class SortTests {
public void testWithSortAscending() {
Query s = new Query().with(Sort.by(Direction.ASC, "name"));
assertEquals(Document.parse("{ \"name\" : 1}"), s.getSortObject());
assertThat(s.getSortObject()).isEqualTo(Document.parse("{ \"name\" : 1}"));
}
@Test
public void testWithSortDescending() {
Query s = new Query().with(Sort.by(Direction.DESC, "name"));
assertEquals(Document.parse("{ \"name\" : -1}"), s.getSortObject());
assertThat(s.getSortObject()).isEqualTo(Document.parse("{ \"name\" : -1}"));
}
@Test // DATADOC-177
public void preservesOrderKeysOnMultipleSorts() {
Query sort = new Query().with(Sort.by(Direction.DESC, "foo").and(Sort.by(Direction.DESC, "bar")));
assertThat(sort.getSortObject(), is(Document.parse("{ \"foo\" : -1 , \"bar\" : -1}")));
assertThat(sort.getSortObject()).isEqualTo(Document.parse("{ \"foo\" : -1 , \"bar\" : -1}"));
}
}

View File

@@ -15,13 +15,11 @@
*/
package org.springframework.data.mongodb.core.query;
import org.bson.Document;
import org.hamcrest.core.IsEqual;
import org.junit.Assert;
import static org.hamcrest.core.IsEqual.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.mongodb.core.DocumentTestUtils;
/**
@@ -35,74 +33,74 @@ public class TextCriteriaUnitTests {
public void shouldNotHaveLanguageField() {
TextCriteria criteria = TextCriteria.forDefaultLanguage();
assertThat(criteria.getCriteriaObject(), equalTo(searchObject("{ }")));
assertThat(criteria.getCriteriaObject()).isEqualTo(searchObject("{ }"));
}
@Test // DATAMONGO-850
public void shouldNotHaveLanguageForNonDefaultLanguageField() {
TextCriteria criteria = TextCriteria.forLanguage("spanish");
assertThat(criteria.getCriteriaObject(), equalTo(searchObject("{ \"$language\" : \"spanish\" }")));
assertThat(criteria.getCriteriaObject()).isEqualTo(searchObject("{ \"$language\" : \"spanish\" }"));
}
@Test // DATAMONGO-850
public void shouldCreateSearchFieldForSingleTermCorrectly() {
TextCriteria criteria = TextCriteria.forDefaultLanguage().matching("cake");
assertThat(criteria.getCriteriaObject(), equalTo(searchObject("{ \"$search\" : \"cake\" }")));
assertThat(criteria.getCriteriaObject()).isEqualTo(searchObject("{ \"$search\" : \"cake\" }"));
}
@Test // DATAMONGO-850
public void shouldCreateSearchFieldCorrectlyForMultipleTermsCorrectly() {
TextCriteria criteria = TextCriteria.forDefaultLanguage().matchingAny("bake", "coffee", "cake");
assertThat(criteria.getCriteriaObject(), equalTo(searchObject("{ \"$search\" : \"bake coffee cake\" }")));
assertThat(criteria.getCriteriaObject()).isEqualTo(searchObject("{ \"$search\" : \"bake coffee cake\" }"));
}
@Test // DATAMONGO-850
public void shouldCreateSearchFieldForPhraseCorrectly() {
TextCriteria criteria = TextCriteria.forDefaultLanguage().matchingPhrase("coffee cake");
Assert.assertThat(DocumentTestUtils.getAsDocument(criteria.getCriteriaObject(), "$text"),
IsEqual.<Document> equalTo(new Document("$search", "\"coffee cake\"")));
assertThat(DocumentTestUtils.getAsDocument(criteria.getCriteriaObject(), "$text"))
.isEqualTo(new Document("$search", "\"coffee cake\""));
}
@Test // DATAMONGO-850
public void shouldCreateNotFieldCorrectly() {
TextCriteria criteria = TextCriteria.forDefaultLanguage().notMatching("cake");
assertThat(criteria.getCriteriaObject(), equalTo(searchObject("{ \"$search\" : \"-cake\" }")));
assertThat(criteria.getCriteriaObject()).isEqualTo(searchObject("{ \"$search\" : \"-cake\" }"));
}
@Test // DATAMONGO-850
public void shouldCreateSearchFieldCorrectlyForNotMultipleTermsCorrectly() {
TextCriteria criteria = TextCriteria.forDefaultLanguage().notMatchingAny("bake", "coffee", "cake");
assertThat(criteria.getCriteriaObject(), equalTo(searchObject("{ \"$search\" : \"-bake -coffee -cake\" }")));
assertThat(criteria.getCriteriaObject()).isEqualTo(searchObject("{ \"$search\" : \"-bake -coffee -cake\" }"));
}
@Test // DATAMONGO-850
public void shouldCreateSearchFieldForNotPhraseCorrectly() {
TextCriteria criteria = TextCriteria.forDefaultLanguage().notMatchingPhrase("coffee cake");
Assert.assertThat(DocumentTestUtils.getAsDocument(criteria.getCriteriaObject(), "$text"),
IsEqual.<Document> equalTo(new Document("$search", "-\"coffee cake\"")));
assertThat(DocumentTestUtils.getAsDocument(criteria.getCriteriaObject(), "$text"))
.isEqualTo(new Document("$search", "-\"coffee cake\""));
}
@Test // DATAMONGO-1455
public void caseSensitiveOperatorShouldBeSetCorrectly() {
TextCriteria criteria = TextCriteria.forDefaultLanguage().matching("coffee").caseSensitive(true);
assertThat(DocumentTestUtils.getAsDocument(criteria.getCriteriaObject(), "$text"),
equalTo(new Document("$search", "coffee").append("$caseSensitive", true)));
assertThat(DocumentTestUtils.getAsDocument(criteria.getCriteriaObject(), "$text"))
.isEqualTo(new Document("$search", "coffee").append("$caseSensitive", true));
}
@Test // DATAMONGO-1456
public void diacriticSensitiveOperatorShouldBeSetCorrectly() {
TextCriteria criteria = TextCriteria.forDefaultLanguage().matching("coffee").diacriticSensitive(true);
assertThat(DocumentTestUtils.getAsDocument(criteria.getCriteriaObject(), "$text"),
equalTo(new Document("$search", "coffee").append("$diacriticSensitive", true)));
assertThat(DocumentTestUtils.getAsDocument(criteria.getCriteriaObject(), "$text"))
.isEqualTo(new Document("$search", "coffee").append("$diacriticSensitive", true));
}
private Document searchObject(String json) {

View File

@@ -15,29 +15,25 @@
*/
package org.springframework.data.mongodb.core.query;
import static org.hamcrest.collection.IsCollectionWithSize.*;
import static org.hamcrest.collection.IsEmptyCollection.*;
import static org.hamcrest.collection.IsIterableContainingInOrder.*;
import static org.hamcrest.core.AnyOf.*;
import static org.hamcrest.core.IsCollectionContaining.*;
import static org.hamcrest.core.IsEqual.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import lombok.ToString;
import java.util.List;
import lombok.ToString;
import org.bson.Document;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.config.AbstractIntegrationTests;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.index.IndexDefinition;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.data.mongodb.core.mapping.Language;
import org.springframework.data.mongodb.core.mapping.TextScore;
@@ -107,8 +103,8 @@ public class TextQueryTests extends AbstractIntegrationTests {
initWithDefaultDocuments();
List<FullTextDoc> result = template.find(new TextQuery("bake coffee cake"), FullTextDoc.class);
assertThat(result, hasSize(3));
assertThat(result, hasItems(BAKE, COFFEE, CAKE));
assertThat(result).hasSize(3);
assertThat(result).contains(BAKE, COFFEE, CAKE);
}
@Test // DATAMONGO-850
@@ -117,7 +113,7 @@ public class TextQueryTests extends AbstractIntegrationTests {
initWithDefaultDocuments();
List<FullTextDoc> result = template.find(new TextQuery("tasmanian devil"), FullTextDoc.class);
assertThat(result, hasSize(0));
assertThat(result).hasSize(0);
}
@Test // DATAMONGO-850
@@ -128,11 +124,11 @@ public class TextQueryTests extends AbstractIntegrationTests {
template.insert(coffee2);
List<FullTextDoc> result = template.find(new TextQuery("bake coffee cake").sortByScore(), FullTextDoc.class);
assertThat(result, hasSize(4));
assertThat(result.get(0), anyOf(equalTo(BAKE), equalTo(coffee2)));
assertThat(result.get(1), anyOf(equalTo(BAKE), equalTo(coffee2)));
assertThat(result.get(2), equalTo(COFFEE));
assertThat(result.get(3), equalTo(CAKE));
assertThat(result).hasSize(4);
assertThat(result.get(0)).isIn(BAKE, coffee2);
assertThat(result.get(1)).isIn(BAKE, coffee2);
assertThat(result.get(2)).isEqualTo(COFFEE);
assertThat(result.get(3)).isEqualTo(CAKE);
}
@Test // DATAMONGO-850
@@ -140,8 +136,8 @@ public class TextQueryTests extends AbstractIntegrationTests {
initWithDefaultDocuments();
List<FullTextDoc> result = template.find(new TextQuery("leche"), FullTextDoc.class);
assertThat(result, hasSize(2));
assertThat(result, hasItems(SPANISH_MILK, FRENCH_MILK));
assertThat(result).hasSize(2);
assertThat(result).contains(SPANISH_MILK, FRENCH_MILK);
}
@Test // DATAMONGO-850
@@ -150,8 +146,8 @@ public class TextQueryTests extends AbstractIntegrationTests {
initWithDefaultDocuments();
List<FullTextDoc> result = template.find(new TextQuery("leche").addCriteria(where("language").is("spanish")),
FullTextDoc.class);
assertThat(result, hasSize(1));
assertThat(result.get(0), equalTo(SPANISH_MILK));
assertThat(result).hasSize(1);
assertThat(result.get(0)).isEqualTo(SPANISH_MILK);
}
@Test // DATAMONGO-850
@@ -160,8 +156,8 @@ public class TextQueryTests extends AbstractIntegrationTests {
initWithDefaultDocuments();
List<FullTextDoc> result = template.find(new TextQuery("bake coffee -cake"), FullTextDoc.class);
assertThat(result, hasSize(2));
assertThat(result, hasItems(BAKE, COFFEE));
assertThat(result).hasSize(2);
assertThat(result).contains(BAKE, COFFEE);
}
@Test // DATAMONGO-976
@@ -172,9 +168,9 @@ public class TextQueryTests extends AbstractIntegrationTests {
List<FullTextDoc> result = template.find(new TextQuery("bake coffee -cake").includeScore().sortByScore(),
FullTextDoc.class);
assertThat(result, hasSize(2));
assertThat(result).hasSize(2);
for (FullTextDoc scoredDoc : result) {
assertTrue(scoredDoc.score > 0F);
assertThat(scoredDoc.score > 0F).isTrue();
}
}
@@ -186,8 +182,8 @@ public class TextQueryTests extends AbstractIntegrationTests {
TextQuery query = TextQuery.queryText(TextCriteria.forDefaultLanguage().matchingPhrase("milk and sugar"));
List<FullTextDoc> result = template.find(query, FullTextDoc.class);
assertThat(result, hasSize(1));
assertThat(result, contains(MILK_AND_SUGAR));
assertThat(result).hasSize(1);
assertThat(result).containsExactly(MILK_AND_SUGAR);
}
@Test // DATAMONGO-850
@@ -198,7 +194,7 @@ public class TextQueryTests extends AbstractIntegrationTests {
TextQuery query = TextQuery.queryText(TextCriteria.forDefaultLanguage().matchingPhrase("milk no sugar"));
List<FullTextDoc> result = template.find(query, FullTextDoc.class);
assertThat(result, empty());
assertThat(result).isEmpty();
}
@Test // DATAMONGO-850
@@ -209,14 +205,14 @@ public class TextQueryTests extends AbstractIntegrationTests {
// page 1
List<FullTextDoc> result = template
.find(new TextQuery("bake coffee cake").sortByScore().with(PageRequest.of(0, 2)), FullTextDoc.class);
assertThat(result, hasSize(2));
assertThat(result, contains(BAKE, COFFEE));
assertThat(result).hasSize(2);
assertThat(result).containsExactly(BAKE, COFFEE);
// page 2
result = template.find(new TextQuery("bake coffee cake").sortByScore().with(PageRequest.of(1, 2)),
FullTextDoc.class);
assertThat(result, hasSize(1));
assertThat(result, contains(CAKE));
assertThat(result).hasSize(1);
assertThat(result).containsExactly(CAKE);
}
private void initWithDefaultDocuments() {

View File

@@ -15,10 +15,10 @@
*/
package org.springframework.data.mongodb.core.query;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.core.query.IsTextQuery.*;
import static org.springframework.data.mongodb.test.util.Assertions.*;
import org.junit.Test;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
@@ -35,17 +35,21 @@ public class TextQueryUnitTests {
@Test // DATAMONGO-850
public void shouldCreateQueryObjectCorrectly() {
assertThat(new TextQuery(QUERY), isTextQuery().searchingFor(QUERY));
assertThat(new TextQuery(QUERY).getQueryObject()).containsEntry("$text.$search", QUERY);
}
@Test // DATAMONGO-850
public void shouldIncludeLanguageInQueryObjectWhenNotNull() {
assertThat(new TextQuery(QUERY, LANGUAGE_SPANISH), isTextQuery().searchingFor(QUERY).inLanguage(LANGUAGE_SPANISH));
assertThat(new TextQuery(QUERY, LANGUAGE_SPANISH).getQueryObject()).containsEntry("$text.$search", QUERY)
.containsEntry("$text.$language", LANGUAGE_SPANISH);
}
@Test // DATAMONGO-850
public void shouldIncludeScoreFieldCorrectly() {
assertThat(new TextQuery(QUERY).includeScore(), isTextQuery().searchingFor(QUERY).returningScore());
TextQuery textQuery = new TextQuery(QUERY).includeScore();
assertThat(textQuery.getQueryObject()).containsEntry("$text.$search", QUERY);
assertThat(textQuery.getFieldsObject()).containsKey("score");
}
@Test // DATAMONGO-850
@@ -54,12 +58,18 @@ public class TextQueryUnitTests {
TextQuery query = new TextQuery(TextCriteria.forDefaultLanguage().matching(QUERY)).includeScore();
query.fields().include("foo");
assertThat(query, isTextQuery().searchingFor(QUERY).returningScore().includingField("foo"));
assertThat(query.getQueryObject()).containsEntry("$text.$search", QUERY);
assertThat(query.getFieldsObject()).containsKeys("score", "foo");
}
@Test // DATAMONGO-850
public void shouldIncludeSortingByScoreCorrectly() {
assertThat(new TextQuery(QUERY).sortByScore(), isTextQuery().searchingFor(QUERY).returningScore().sortingByScore());
TextQuery textQuery = new TextQuery(QUERY).sortByScore();
assertThat(textQuery.getQueryObject()).containsEntry("$text.$search", QUERY);
assertThat(textQuery.getFieldsObject()).containsKey("score");
assertThat(textQuery.getSortObject()).containsKey("score");
}
@Test // DATAMONGO-850
@@ -69,15 +79,19 @@ public class TextQueryUnitTests {
query.with(Sort.by(Direction.DESC, "foo"));
query.sortByScore();
assertThat(query,
isTextQuery().searchingFor(QUERY).returningScore().sortingByScore().sortingBy("foo", Direction.DESC));
assertThat(query.getQueryObject()).containsEntry("$text.$search", QUERY);
assertThat(query.getFieldsObject()).containsKeys("score");
assertThat(query.getSortObject()).containsEntry("foo", -1).containsKey("score");
}
@Test // DATAMONGO-850
public void shouldUseCustomFieldnameForScoring() {
TextQuery query = new TextQuery(QUERY).includeScore("customFieldForScore").sortByScore();
assertThat(query, isTextQuery().searchingFor(QUERY).returningScoreAs("customFieldForScore").sortingByScore());
assertThat(query.getQueryObject()).containsEntry("$text.$search", QUERY);
assertThat(query.getFieldsObject()).containsKeys("customFieldForScore");
assertThat(query.getSortObject()).containsKey("customFieldForScore");
}
}

View File

@@ -16,7 +16,6 @@
package org.springframework.data.mongodb.core.query;
import static org.assertj.core.api.Assertions.*;
import static org.hamcrest.Matchers.*;
import org.junit.Before;
import org.junit.Test;
@@ -32,7 +31,7 @@ public class UntypedExampleMatcherUnitTests {
ExampleMatcher matcher;
@Before
public void setUp() throws Exception {
public void setUp() {
matcher = UntypedExampleMatcher.matching();
}
@@ -125,7 +124,7 @@ public class UntypedExampleMatcherUnitTests {
matcher = UntypedExampleMatcher.matching().withIgnorePaths("foo", "bar", "foo");
ExampleMatcher configuredExampleSpec = matcher.withIgnoreCase();
assertThat(matcher).isNotEqualTo(sameInstance(configuredExampleSpec));
assertThat(matcher).isNotSameAs(configuredExampleSpec);
assertThat(matcher.getIgnoredPaths()).hasSize(2);
assertThat(matcher.isIgnoreCaseEnabled()).isFalse();

View File

@@ -15,13 +15,12 @@
*/
package org.springframework.data.mongodb.core.script;
import static org.hamcrest.core.IsEqual.*;
import static org.hamcrest.core.IsNull.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.util.ObjectUtils;
/**
@@ -54,8 +53,8 @@ public class ExecutableMongoScriptUnitTests {
ExecutableMongoScript script = new ExecutableMongoScript(jsFunction);
assertThat(script.getCode(), notNullValue());
assertThat(script.getCode().toString(), equalTo(jsFunction));
assertThat(script.getCode()).isNotNull();
assertThat(script.getCode().toString()).isEqualTo(jsFunction);
}
private void expectException(Class<?> type, String... messageFragments) {

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core.script;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
@@ -49,6 +48,6 @@ public class NamedMongoScriptUnitTests {
String jsFunction = "function(x) { return x; }";
assertThat(new NamedMongoScript("echo", jsFunction).getCode(), is(jsFunction));
assertThat(new NamedMongoScript("echo", jsFunction).getCode()).isEqualTo(jsFunction);
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.core.spel;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Arrays;
import java.util.Collection;
@@ -26,6 +25,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.expression.spel.ExpressionState;
import org.springframework.expression.spel.SpelNode;
import org.springframework.expression.spel.ast.OpDivide;
@@ -59,7 +59,7 @@ public class ExpressionNodeUnitTests {
public void createsOperatorNodeForOperations() {
for (SpelNode operator : operators) {
assertThat(ExpressionNode.from(operator, state), is(instanceOf(OperatorNode.class)));
assertThat(ExpressionNode.from(operator, state)).isInstanceOf(OperatorNode.class);
}
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.mongodb.gridfs;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.regex.Pattern;
@@ -35,8 +34,8 @@ public class AntPathUnitTests {
AntPath path = new AntPath("**/foo/*-bar.xml");
String regex = path.toRegex();
assertThat(Pattern.matches(regex, "foo/bar/foo/foo-bar.xml"), is(true));
assertThat(Pattern.matches(regex, "foo/bar/foo/bar/foo-bar.xml"), is(false));
assertThat(regex, is(".*\\Q/foo/\\E[^/]*\\Q-bar.xml\\E"));
assertThat(Pattern.matches(regex, "foo/bar/foo/foo-bar.xml")).isTrue();
assertThat(Pattern.matches(regex, "foo/bar/foo/bar/foo-bar.xml")).isFalse();
assertThat(regex).isEqualTo(".*\\Q/foo/\\E[^/]*\\Q-bar.xml\\E");
}
}

View File

@@ -15,13 +15,13 @@
*/
package org.springframework.data.mongodb.monitor;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.net.UnknownHostException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -59,8 +59,8 @@ public class MongoMonitorIntegrationTests {
throw e;
}
assertThat(hostName, is(notNullValue()));
assertThat(hostName, is("127.0.0.1"));
assertThat(hostName).isNotNull();
assertThat(hostName).isEqualTo("127.0.0.1");
}
@Test

Some files were not shown because too many files have changed in this diff Show More