Browse Source

DATAMONGO-1609 - Fix failing tests.

Fix issues pointed out by failing tests. Main focus was to restore functionality and not a Java 8 code cleanup. So, this one still needs some love and polishing.
pull/371/head
Christoph Strobl 9 years ago committed by Oliver Gierke
parent
commit
288f244c34
  1. 6
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java
  2. 12
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoTemplate.java
  3. 2
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultDbRefResolverCallback.java
  4. 7
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultMongoTypeMapper.java
  5. 11
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MappingMongoConverter.java
  6. 9
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MongoExampleMapper.java
  7. 16
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java
  8. 2
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexCreator.java
  9. 6
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexResolver.java
  10. 7
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/NearQuery.java
  11. 5
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Query.java
  12. 2
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/cdi/MongoRepositoryBean.java
  13. 5
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SpringDataMongodbQuery.java
  14. 2
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SpringDataMongodbSerializer.java
  15. 4
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AuditingViaJavaConfigRepositoriesTests.java
  16. 31
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoExceptionTranslatorUnitTests.java
  17. 2
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoOperationsUnitTests.java
  18. 6
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateTests.java
  19. 14
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateUnitTests.java
  20. 4
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/QueryCursorPreparerUnitTests.java
  21. 4
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ReactiveMongoTemplateTests.java
  22. 10
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/DbRefMappingMongoConverterUnitTests.java
  23. 3
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/ReflectiveDBRefResolverUnitTests.java
  24. 8
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/index/PathUnitTests.java
  25. 2
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/BasicMongoPersistentEntityUnitTests.java
  26. 5
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/MongoMappingContextUnitTests.java
  27. 8
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/IsQuery.java
  28. 2
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/IsTextQuery.java
  29. 16
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/NearQueryUnitTests.java
  30. 2
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/TextQueryTests.java
  31. 3
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/AbstractPersonRepositoryIntegrationTests.java
  32. 3
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/ComplexIdRepositoryIntegrationTests.java
  33. 2
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/cdi/CdiExtensionIntegrationTests.java
  34. 4
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/cdi/CdiPersonRepository.java
  35. 12
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/query/AbstractMongoQueryUnitTests.java
  36. 4
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/query/ReactiveMongoQueryExecutionUnitTests.java
  37. 3
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/query/ReactiveStringBasedMongoQueryUnitTests.java
  38. 2
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/query/StringBasedMongoQueryUnitTests.java
  39. 4
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/support/MongoRepositoryFactoryUnitTests.java

6
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java

@ -1172,7 +1172,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
public UpdateResult doInCollection(MongoCollection<Document> collection) public UpdateResult doInCollection(MongoCollection<Document> collection)
throws MongoException, DataAccessException { throws MongoException, DataAccessException {
Optional<? extends MongoPersistentEntity<?>> entity = entityClass == null ? null Optional<? extends MongoPersistentEntity<?>> entity = entityClass == null ? Optional.empty()
: getPersistentEntity(entityClass); : getPersistentEntity(entityClass);
increaseVersionForUpdateIfNecessary(entity, update); increaseVersionForUpdateIfNecessary(entity, update);
@ -2011,7 +2011,9 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
PersistentPropertyAccessor accessor = entity.getPropertyAccessor(savedObject); PersistentPropertyAccessor accessor = entity.getPropertyAccessor(savedObject);
Optional<Object> value = accessor.getProperty(idProp); Optional<Object> value = accessor.getProperty(idProp);
value.ifPresent(it -> new ConvertingPropertyAccessor(accessor, conversionService).setProperty(idProp, value)); if(!value.isPresent()) {
new ConvertingPropertyAccessor(accessor, conversionService).setProperty(idProp, Optional.of(id));
}
}); });
} }

12
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoTemplate.java

@ -755,7 +755,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
final Document Document = query == null ? null final Document Document = query == null ? null
: queryMapper.getMappedObject(query.getQueryObject(), : queryMapper.getMappedObject(query.getQueryObject(),
entityClass == null ? null : mappingContext.getPersistentEntity(entityClass)); entityClass == null ? Optional.empty() : mappingContext.getPersistentEntity(entityClass));
return collection.count(Document); return collection.count(Document);
}); });
@ -976,8 +976,8 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
ReactiveMongoTemplate.this.assertUpdateableIdIfNotSet(objectToSave); ReactiveMongoTemplate.this.assertUpdateableIdIfNotSet(objectToSave);
// Create query for entity with the id and old version // Create query for entity with the id and old version
Object id = convertingAccessor.getProperty(idProperty); Optional<Object> id = convertingAccessor.getProperty(idProperty);
Query query = new Query(Criteria.where(idProperty.getName()).is(id).and(versionProperty.getName()).is(version)); Query query = new Query(Criteria.where(idProperty.getName()).is(id.get()).and(versionProperty.getName()).is(version.get()));
// Bump version number // Bump version number
convertingAccessor.setProperty(versionProperty, Optional.of(versionNumber.orElse(0).longValue() + 1)); convertingAccessor.setProperty(versionProperty, Optional.of(versionNumber.orElse(0).longValue() + 1));
@ -1308,8 +1308,8 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
throw new MappingException("No id property found for object of type " + objectType); throw new MappingException("No id property found for object of type " + objectType);
} }
Object idValue = entity.get().getPropertyAccessor(object).getProperty(idProp); Optional<Object> idValue = entity.get().getPropertyAccessor(object).getProperty(idProp);
return Collections.singletonMap(idProp.getFieldName(), idValue).entrySet().iterator().next(); return Collections.singletonMap(idProp.getFieldName(), idValue.get()).entrySet().iterator().next();
} }
/** /**
@ -1706,7 +1706,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
MongoPersistentEntity<?> entity = mappingContext.getRequiredPersistentEntity(savedObject.getClass()); MongoPersistentEntity<?> entity = mappingContext.getRequiredPersistentEntity(savedObject.getClass());
PersistentPropertyAccessor accessor = entity.getPropertyAccessor(savedObject); PersistentPropertyAccessor accessor = entity.getPropertyAccessor(savedObject);
if (accessor.getProperty(idProp) != null) { if (accessor.getProperty(idProp).isPresent()) {
return; return;
} }

2
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultDbRefResolverCallback.java

@ -57,6 +57,6 @@ class DefaultDbRefResolverCallback implements DbRefResolverCallback {
*/ */
@Override @Override
public Object resolve(MongoPersistentProperty property) { public Object resolve(MongoPersistentProperty property) {
return resolver.getValueInternal(property, surroundingObject, evaluator, path); return resolver.getValueInternal(property, surroundingObject, evaluator, path).orElse(null);
} }
} }

7
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultMongoTypeMapper.java

@ -35,6 +35,7 @@ import org.springframework.data.util.TypeInformation;
import com.mongodb.BasicDBList; import com.mongodb.BasicDBList;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import org.springframework.util.ObjectUtils;
/** /**
* Default implementation of {@link MongoTypeMapper} allowing configuration of the key to lookup and store type * Default implementation of {@link MongoTypeMapper} allowing configuration of the key to lookup and store type
@ -108,10 +109,10 @@ public class DefaultMongoTypeMapper extends DefaultTypeMapper<Bson> implements M
for (Class<?> restrictedType : restrictedTypes) { for (Class<?> restrictedType : restrictedTypes) {
Object typeAlias = getAliasFor(ClassTypeInformation.from(restrictedType)); Alias typeAlias = getAliasFor(ClassTypeInformation.from(restrictedType));
if (typeAlias != null) { if (typeAlias != null && !ObjectUtils.nullSafeEquals(Alias.NONE, typeAlias) && typeAlias.getValue().isPresent()) {
restrictedMappedTypes.add(typeAlias); restrictedMappedTypes.add(typeAlias.getValue().get());
} }
} }

11
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MappingMongoConverter.java

@ -55,6 +55,7 @@ import org.springframework.data.mapping.model.SpELContext;
import org.springframework.data.mapping.model.SpELExpressionEvaluator; import org.springframework.data.mapping.model.SpELExpressionEvaluator;
import org.springframework.data.mapping.model.SpELExpressionParameterValueProvider; import org.springframework.data.mapping.model.SpELExpressionParameterValueProvider;
import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.convert.MongoConverters.ObjectIdToBigIntegerConverter;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity; import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty; import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.core.mapping.event.AfterConvertEvent; import org.springframework.data.mongodb.core.mapping.event.AfterConvertEvent;
@ -240,7 +241,9 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
} }
// Retrieve persistent entity info // Retrieve persistent entity info
return read((MongoPersistentEntity<S>) mappingContext.getRequiredPersistentEntity(typeToUse), (Document) bson, Document target = bson instanceof BasicDBObject ? new Document((BasicDBObject)bson) : (Document) bson;
return read((MongoPersistentEntity<S>) mappingContext.getRequiredPersistentEntity(typeToUse), target,
path); path);
} }
@ -271,7 +274,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
DocumentAccessor documentAccessor = new DocumentAccessor(bson); DocumentAccessor documentAccessor = new DocumentAccessor(bson);
// make sure id property is set before all other properties // make sure id property is set before all other properties
Object idValue = idProperty.filter(it -> documentAccessor.hasValue(it)).map(it -> { Optional<Object> idValue = idProperty.filter(it -> documentAccessor.hasValue(it)).map(it -> {
Optional<Object> value = getValueInternal(it, bson, evaluator, path); Optional<Object> value = getValueInternal(it, bson, evaluator, path);
accessor.setProperty(it, value); accessor.setProperty(it, value);
@ -280,7 +283,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
}); });
final ObjectPath currentPath = path.push(result, entity, final ObjectPath currentPath = path.push(result, entity,
idValue != null ? idProperty.map(it -> bson.get(it.getFieldName())).orElse(null) : null); idValue.isPresent() ? idProperty.map(it -> bson.get(it.getFieldName())).orElse(null) : null);
// Set properties not already set in the constructor // Set properties not already set in the constructor
entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() { entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() {
@ -867,7 +870,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
} }
return dbRefResolver.createDbRef(property == null ? null : property.getDBRef(), entity, return dbRefResolver.createDbRef(property == null ? null : property.getDBRef(), entity,
idMapper.convertId(Optional.of(id))); idMapper.convertId(id instanceof Optional ? (Optional)id : Optional.ofNullable(id)).orElse(null));
}).orElseThrow(() -> new MappingException("No id property found on class " + entity.getType())); }).orElseThrow(() -> new MappingException("No id property found on class " + entity.getType()));
} }

9
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MongoExampleMapper.java

@ -23,6 +23,7 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.Stack; import java.util.Stack;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -98,9 +99,9 @@ public class MongoExampleMapper {
Document reference = (Document) converter.convertToMongoType(example.getProbe()); Document reference = (Document) converter.convertToMongoType(example.getProbe());
Optionals.ifAllPresent(entity.getIdProperty(), // if(entity.getIdProperty().isPresent() && !entity.getIdentifierAccessor(example.getProbe()).getIdentifier().isPresent()) {
entity.getIdentifierAccessor(example.getProbe()).getIdentifier(), // reference.remove(entity.getIdProperty().get().getFieldName());
(property, identifier) -> reference.remove(property.getFieldName())); }
ExampleMatcherAccessor matcherAccessor = new ExampleMatcherAccessor(example.getMatcher()); ExampleMatcherAccessor matcherAccessor = new ExampleMatcherAccessor(example.getMatcher());
@ -241,7 +242,7 @@ public class MongoExampleMapper {
} }
private boolean isEmptyIdProperty(Entry<String, Object> entry) { private boolean isEmptyIdProperty(Entry<String, Object> entry) {
return entry.getKey().equals("_id") && entry.getValue() == null; return entry.getKey().equals("_id") && entry.getValue() == null || entry.getValue().equals(Optional.empty());
} }
private void applyStringMatcher(Map.Entry<String, Object> entry, StringMatcher stringMatcher, boolean ignoreCase) { private void applyStringMatcher(Map.Entry<String, Object> entry, StringMatcher stringMatcher, boolean ignoreCase) {

16
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java

@ -318,11 +318,11 @@ public class QueryMapper {
String inKey = valueDbo.containsField("$in") ? "$in" : "$nin"; String inKey = valueDbo.containsField("$in") ? "$in" : "$nin";
List<Object> ids = new ArrayList<Object>(); List<Object> ids = new ArrayList<Object>();
for (Object id : (Iterable<?>) valueDbo.get(inKey)) { for (Object id : (Iterable<?>) valueDbo.get(inKey)) {
ids.add(convertId(id)); ids.add(convertId(id).get());
} }
resultDbo.put(inKey, ids); resultDbo.put(inKey, ids);
} else if (valueDbo.containsField("$ne")) { } else if (valueDbo.containsField("$ne")) {
resultDbo.put("$ne", convertId(valueDbo.get("$ne"))); resultDbo.put("$ne", convertId(valueDbo.get("$ne")).get());
} else { } else {
return getMappedObject(resultDbo, Optional.empty()); return getMappedObject(resultDbo, Optional.empty());
} }
@ -337,18 +337,18 @@ public class QueryMapper {
String inKey = valueDbo.containsKey("$in") ? "$in" : "$nin"; String inKey = valueDbo.containsKey("$in") ? "$in" : "$nin";
List<Object> ids = new ArrayList<Object>(); List<Object> ids = new ArrayList<Object>();
for (Object id : (Iterable<?>) valueDbo.get(inKey)) { for (Object id : (Iterable<?>) valueDbo.get(inKey)) {
ids.add(convertId(id)); ids.add(convertId(id).orElse(null));
} }
resultDbo.put(inKey, ids); resultDbo.put(inKey, ids);
} else if (valueDbo.containsKey("$ne")) { } else if (valueDbo.containsKey("$ne")) {
resultDbo.put("$ne", convertId(valueDbo.get("$ne"))); resultDbo.put("$ne", convertId(valueDbo.get("$ne")).orElse(null));
} else { } else {
return getMappedObject(resultDbo, Optional.empty()); return getMappedObject(resultDbo, Optional.empty());
} }
return resultDbo; return resultDbo;
} else { } else {
return convertId(value); return convertId(value).orElse(null);
} }
} }
@ -461,7 +461,7 @@ public class QueryMapper {
if (source instanceof DBRef) { if (source instanceof DBRef) {
DBRef ref = (DBRef) source; DBRef ref = (DBRef) source;
return new DBRef(ref.getCollectionName(), convertId(ref.getId())); return new DBRef(ref.getCollectionName(), convertId(ref.getId()).get());
} }
if (source instanceof Iterable) { if (source instanceof Iterable) {
@ -538,7 +538,7 @@ public class QueryMapper {
} }
private Optional<Object> convertId(Object id) { private Optional<Object> convertId(Object id) {
return convertId(Optional.of(id)); return convertId(Optional.ofNullable(id));
} }
/** /**
@ -857,7 +857,7 @@ public class QueryMapper {
@Override @Override
public MongoPersistentEntity<?> getPropertyEntity() { public MongoPersistentEntity<?> getPropertyEntity() {
MongoPersistentProperty property = getProperty(); MongoPersistentProperty property = getProperty();
return property == null ? null : mappingContext.getRequiredPersistentEntity(property); return property == null ? null : mappingContext.getPersistentEntity(property).orElse(null);
} }
/* /*

2
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexCreator.java

@ -131,7 +131,7 @@ public class MongoPersistentEntityIndexCreator implements ApplicationListener<Ma
private void checkForAndCreateIndexes(MongoPersistentEntity<?> entity) { private void checkForAndCreateIndexes(MongoPersistentEntity<?> entity) {
if (entity.findAnnotation(Document.class) != null) { if (entity.findAnnotation(Document.class).isPresent()) {
for (IndexDefinitionHolder indexToCreate : indexResolver.resolveIndexFor(entity.getTypeInformation())) { for (IndexDefinitionHolder indexToCreate : indexResolver.resolveIndexFor(entity.getTypeInformation())) {
createIndex(indexToCreate); createIndex(indexToCreate);
} }

6
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexResolver.java

@ -261,13 +261,13 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
String propertyDotPath = (StringUtils.hasText(dotPath) ? dotPath + "." : "") String propertyDotPath = (StringUtils.hasText(dotPath) ? dotPath + "." : "")
+ persistentProperty.getFieldName(); + persistentProperty.getFieldName();
Float weight = indexed != null ? indexed.get().weight() Float weight = indexed.isPresent() ? indexed.get().weight()
: (includeOptions.getParentFieldSpec() != null ? includeOptions.getParentFieldSpec().getWeight() : 1.0F); : (includeOptions.getParentFieldSpec() != null ? includeOptions.getParentFieldSpec().getWeight() : 1.0F);
if (persistentProperty.isEntity()) { if (persistentProperty.isEntity()) {
TextIndexIncludeOptions optionsForNestedType = includeOptions; TextIndexIncludeOptions optionsForNestedType = includeOptions;
if (!IncludeStrategy.FORCE.equals(includeOptions.getStrategy()) && indexed != null) { if (!IncludeStrategy.FORCE.equals(includeOptions.getStrategy()) && indexed.isPresent()) {
optionsForNestedType = new TextIndexIncludeOptions(IncludeStrategy.FORCE, optionsForNestedType = new TextIndexIncludeOptions(IncludeStrategy.FORCE,
new TextIndexedFieldSpec(propertyDotPath, weight)); new TextIndexedFieldSpec(propertyDotPath, weight));
} }
@ -281,7 +281,7 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
LOGGER.info(String.format("Potentially invalid index structure discovered. Breaking operation for %s.", LOGGER.info(String.format("Potentially invalid index structure discovered. Breaking operation for %s.",
entity.getName()), e); entity.getName()), e);
} }
} else if (includeOptions.isForce() || indexed != null) { } else if (includeOptions.isForce() || indexed.isPresent()) {
indexDefinitionBuilder.onField(propertyDotPath, weight); indexDefinitionBuilder.onField(propertyDotPath, weight);
} }
} }

7
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/NearQuery.java

@ -25,6 +25,7 @@ import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Metrics; import org.springframework.data.geo.Metrics;
import org.springframework.data.geo.Point; import org.springframework.data.geo.Point;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/** /**
* Builder class to build near-queries. * Builder class to build near-queries.
@ -150,8 +151,10 @@ public final class NearQuery {
public NearQuery with(Pageable pageable) { public NearQuery with(Pageable pageable) {
Assert.notNull(pageable, "Pageable must not be 'null'."); Assert.notNull(pageable, "Pageable must not be 'null'.");
this.num = pageable.getOffset() + pageable.getPageSize(); if(!ObjectUtils.nullSafeEquals(Pageable.NONE, pageable)) {
this.skip = pageable.getOffset(); this.num = pageable.getOffset() + pageable.getPageSize();
this.skip = pageable.getOffset();
}
return this; return this;
} }

5
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Query.java

@ -33,6 +33,7 @@ import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order; import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.InvalidMongoDbApiUsageException; import org.springframework.data.mongodb.InvalidMongoDbApiUsageException;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/** /**
* @author Thomas Risberg * @author Thomas Risberg
@ -151,7 +152,7 @@ public class Query {
*/ */
public Query with(Pageable pageable) { public Query with(Pageable pageable) {
if (pageable == null) { if (pageable == null || ObjectUtils.nullSafeEquals(Pageable.NONE, pageable)) {
return this; return this;
} }
@ -169,7 +170,7 @@ public class Query {
*/ */
public Query with(Sort sort) { public Query with(Sort sort) {
if (sort == null) { if (sort == null || ObjectUtils.nullSafeEquals(Sort.unsorted(), sort)) {
return this; return this;
} }

2
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/cdi/MongoRepositoryBean.java

@ -68,6 +68,6 @@ public class MongoRepositoryBean<T> extends CdiRepositoryBean<T> {
MongoOperations mongoOperations = getDependencyInstance(operations, MongoOperations.class); MongoOperations mongoOperations = getDependencyInstance(operations, MongoOperations.class);
MongoRepositoryFactory factory = new MongoRepositoryFactory(mongoOperations); MongoRepositoryFactory factory = new MongoRepositoryFactory(mongoOperations);
return factory.getRepository(repositoryType, customImplementation); return customImplementation.isPresent() ? factory.getRepository(repositoryType, customImplementation.get()) : factory.getRepository(repositoryType);
} }
} }

5
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SpringDataMongodbQuery.java

@ -15,6 +15,7 @@
*/ */
package org.springframework.data.mongodb.repository.support; package org.springframework.data.mongodb.repository.support;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.MongoTemplate;
@ -58,7 +59,9 @@ public class SpringDataMongodbQuery<T> extends AbstractMongodbQuery<T, SpringDat
@Override @Override
public T apply(DBObject input) { public T apply(DBObject input) {
return operations.getConverter().read(type, (BasicDBObject) input);
;
return operations.getConverter().read(type, new Document((BasicDBObject) input));
} }
}, new SpringDataMongodbSerializer(operations.getConverter())); }, new SpringDataMongodbSerializer(operations.getConverter()));

2
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SpringDataMongodbSerializer.java

@ -120,6 +120,8 @@ class SpringDataMongodbSerializer extends MongodbSerializer {
@Override @Override
protected DBObject asDBObject(String key, Object value) { protected DBObject asDBObject(String key, Object value) {
value = value instanceof Optional ? ((Optional)value).orElse(null) : value;
if (ID_KEY.equals(key)) { if (ID_KEY.equals(key)) {
DBObject superIdValue = super.asDBObject(key, value); DBObject superIdValue = super.asDBObject(key, value);
Document mappedIdValue = mapper.getMappedObject((BasicDBObject) superIdValue, Optional.empty()); Document mappedIdValue = mapper.getMappedObject((BasicDBObject) superIdValue, Optional.empty());

4
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AuditingViaJavaConfigRepositoriesTests.java

@ -19,6 +19,8 @@ import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import java.util.Optional;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -82,7 +84,7 @@ public class AuditingViaJavaConfigRepositoriesTests {
@Test // DATAMONGO-792, DATAMONGO-883 @Test // DATAMONGO-792, DATAMONGO-883
public void basicAuditing() { public void basicAuditing() {
doReturn(this.auditor).when(this.auditorAware).getCurrentAuditor(); doReturn(Optional.of(this.auditor)).when(this.auditorAware).getCurrentAuditor();
AuditablePerson savedUser = auditablePersonRepository.save(new AuditablePerson("user")); AuditablePerson savedUser = auditablePersonRepository.save(new AuditablePerson("user"));

31
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoExceptionTranslatorUnitTests.java

@ -22,6 +22,9 @@ import static org.mockito.Mockito.*;
import java.io.IOException; import java.io.IOException;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import com.mongodb.WriteConcern;
import org.bson.BsonDocument;
import org.bson.Document;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -48,15 +51,10 @@ import com.mongodb.ServerAddress;
* @author Oliver Gierke * @author Oliver Gierke
* @author Christoph Strobl * @author Christoph Strobl
*/ */
@RunWith(MockitoJUnitRunner.class)
public class MongoExceptionTranslatorUnitTests { public class MongoExceptionTranslatorUnitTests {
MongoExceptionTranslator translator; MongoExceptionTranslator translator;
@Mock com.mongodb.DuplicateKeyException exception;
@Mock MongoSocketException socketException;
@Mock MongoCursorNotFoundException cursorNotFoundException;
@Before @Before
public void setUp() { public void setUp() {
translator = new MongoExceptionTranslator(); translator = new MongoExceptionTranslator();
@ -65,30 +63,27 @@ public class MongoExceptionTranslatorUnitTests {
@Test @Test
public void translateDuplicateKey() { public void translateDuplicateKey() {
DataAccessException translatedException = translator.translateExceptionIfPossible(exception); expectExceptionWithCauseMessage(
expectExceptionWithCauseMessage(translatedException, DuplicateKeyException.class, null); translator.translateExceptionIfPossible(
new com.mongodb.DuplicateKeyException(new BsonDocument(), new ServerAddress(), null)),
DuplicateKeyException.class, null);
} }
@Test @Test
public void translateSocketException() { public void translateSocketException() {
when(socketException.getMessage()).thenReturn("IOException"); expectExceptionWithCauseMessage(
when(socketException.getCause()).thenReturn(new IOException("IOException")); translator.translateExceptionIfPossible(new MongoSocketException("IOException", new ServerAddress())),
DataAccessException translatedException = translator.translateExceptionIfPossible(socketException); DataAccessResourceFailureException.class, "IOException");
expectExceptionWithCauseMessage(translatedException, DataAccessResourceFailureException.class, "IOException");
} }
@Test @Test
public void translateCursorNotFound() throws UnknownHostException { public void translateCursorNotFound() throws UnknownHostException {
when(cursorNotFoundException.getCode()).thenReturn(1); expectExceptionWithCauseMessage(
when(cursorNotFoundException.getServerAddress()).thenReturn(new ServerAddress()); translator.translateExceptionIfPossible(new MongoCursorNotFoundException(1L, new ServerAddress())),
DataAccessResourceFailureException.class);
DataAccessException translatedException = translator.translateExceptionIfPossible(cursorNotFoundException);
expectExceptionWithCauseMessage(translatedException, DataAccessResourceFailureException.class);
} }
@Test @Test

2
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoOperationsUnitTests.java

@ -209,7 +209,7 @@ public abstract class MongoOperationsUnitTests {
public void doWith(MongoOperations operations) { public void doWith(MongoOperations operations) {
operations.findAll(Object.class); operations.findAll(Object.class);
} }
}.assertDataAccessException(); }.assertException(IllegalArgumentException.class);
} }
@Test @Test

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

@ -1493,7 +1493,7 @@ public class MongoTemplateTests {
template.save(map, "maps"); template.save(map, "maps");
} }
@Test(expected = MappingException.class) // DATAMONGO-549 @Test(expected = IllegalArgumentException.class) // DATAMONGO-549
public void savesMongoPrimitiveObjectCorrectly() { public void savesMongoPrimitiveObjectCorrectly() {
template.save(new Object(), "collection"); template.save(new Object(), "collection");
} }
@ -1512,7 +1512,7 @@ public class MongoTemplateTests {
assertThat(document.containsKey("_id"), is(true)); assertThat(document.containsKey("_id"), is(true));
} }
@Test(expected = InvalidDataAccessApiUsageException.class) // DATAMONGO-550 @Test(expected = IllegalArgumentException.class) // DATAMONGO-550
public void rejectsPlainObjectWithOutExplicitCollection() { public void rejectsPlainObjectWithOutExplicitCollection() {
org.bson.Document document = new org.bson.Document("foo", "bar"); org.bson.Document document = new org.bson.Document("foo", "bar");
@ -2507,7 +2507,7 @@ public class MongoTemplateTests {
template.save(document); template.save(document);
Query query = query(where("id").is(document.id).and("models._id").exists(true)); Query query = query(where("id").is(document.id).and("models.value").exists(true));
Update update = new Update().set("models.$.value", "mongodb"); Update update = new Update().set("models.$.value", "mongodb");
template.findAndModify(query, update, DocumentWithCollection.class); template.findAndModify(query, update, DocumentWithCollection.class);

14
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateUnitTests.java

@ -104,13 +104,11 @@ public class MongoTemplateUnitTests extends MongoOperationsUnitTests {
@Before @Before
public void setUp() { public void setUp() {
// when(cursor.copy()).thenReturn(cursor);
when(findIterable.iterator()).thenReturn(cursor); when(findIterable.iterator()).thenReturn(cursor);
when(factory.getDb()).thenReturn(db); when(factory.getDb()).thenReturn(db);
when(factory.getExceptionTranslator()).thenReturn(exceptionTranslator); when(factory.getExceptionTranslator()).thenReturn(exceptionTranslator);
when(db.getCollection(Mockito.any(String.class), eq(Document.class))).thenReturn(collection); when(db.getCollection(Mockito.any(String.class), eq(Document.class))).thenReturn(collection);
when(collection.find(Mockito.any(org.bson.Document.class))).thenReturn(findIterable); when(collection.find(Mockito.any(org.bson.Document.class))).thenReturn(findIterable);
when(findIterable.limit(anyInt())).thenReturn(findIterable);
when(findIterable.sort(Mockito.any(org.bson.Document.class))).thenReturn(findIterable); when(findIterable.sort(Mockito.any(org.bson.Document.class))).thenReturn(findIterable);
when(findIterable.modifiers(Mockito.any(org.bson.Document.class))).thenReturn(findIterable); when(findIterable.modifiers(Mockito.any(org.bson.Document.class))).thenReturn(findIterable);
@ -131,8 +129,8 @@ public class MongoTemplateUnitTests extends MongoOperationsUnitTests {
@Test(expected = DataAccessException.class) @Test(expected = DataAccessException.class)
public void removeHandlesMongoExceptionProperly() throws Exception { public void removeHandlesMongoExceptionProperly() throws Exception {
MongoTemplate template = mockOutGetDb(); MongoTemplate template = mockOutGetDb();
when(db.getCollection("collection")).thenThrow(new MongoException("Exception!"));
template.remove(null, "collection"); template.remove(null, "collection");
} }
@ -338,8 +336,6 @@ public class MongoTemplateUnitTests extends MongoOperationsUnitTests {
@Test // DATAMONGO-1166 @Test // DATAMONGO-1166
public void aggregateShouldHonorReadPreferenceWhenSet() { public void aggregateShouldHonorReadPreferenceWhenSet() {
when(db.runCommand(Mockito.any(org.bson.Document.class), Mockito.any(ReadPreference.class)))
.thenReturn(mock(Document.class));
when(db.runCommand(Mockito.any(org.bson.Document.class), Mockito.any(ReadPreference.class), eq(Document.class))) when(db.runCommand(Mockito.any(org.bson.Document.class), Mockito.any(ReadPreference.class), eq(Document.class)))
.thenReturn(mock(Document.class)); .thenReturn(mock(Document.class));
template.setReadPreference(ReadPreference.secondary()); template.setReadPreference(ReadPreference.secondary());
@ -353,8 +349,6 @@ public class MongoTemplateUnitTests extends MongoOperationsUnitTests {
@Test // DATAMONGO-1166 @Test // DATAMONGO-1166
public void aggregateShouldIgnoreReadPreferenceWhenNotSet() { public void aggregateShouldIgnoreReadPreferenceWhenNotSet() {
when(db.runCommand(Mockito.any(org.bson.Document.class), Mockito.any(ReadPreference.class)))
.thenReturn(mock(Document.class));
when(db.runCommand(Mockito.any(org.bson.Document.class), eq(org.bson.Document.class))) when(db.runCommand(Mockito.any(org.bson.Document.class), eq(org.bson.Document.class)))
.thenReturn(mock(Document.class)); .thenReturn(mock(Document.class));
@ -366,8 +360,6 @@ public class MongoTemplateUnitTests extends MongoOperationsUnitTests {
@Test // DATAMONGO-1166 @Test // DATAMONGO-1166
public void geoNearShouldHonorReadPreferenceWhenSet() { public void geoNearShouldHonorReadPreferenceWhenSet() {
when(db.runCommand(Mockito.any(org.bson.Document.class), Mockito.any(ReadPreference.class)))
.thenReturn(mock(Document.class));
when(db.runCommand(Mockito.any(org.bson.Document.class), Mockito.any(ReadPreference.class), eq(Document.class))) when(db.runCommand(Mockito.any(org.bson.Document.class), Mockito.any(ReadPreference.class), eq(Document.class)))
.thenReturn(mock(Document.class)); .thenReturn(mock(Document.class));
template.setReadPreference(ReadPreference.secondary()); template.setReadPreference(ReadPreference.secondary());
@ -382,8 +374,6 @@ public class MongoTemplateUnitTests extends MongoOperationsUnitTests {
@Test // DATAMONGO-1166 @Test // DATAMONGO-1166
public void geoNearShouldIgnoreReadPreferenceWhenNotSet() { public void geoNearShouldIgnoreReadPreferenceWhenNotSet() {
when(db.runCommand(Mockito.any(Document.class), Mockito.any(ReadPreference.class)))
.thenReturn(mock(Document.class));
when(db.runCommand(Mockito.any(Document.class), eq(Document.class))).thenReturn(mock(Document.class)); when(db.runCommand(Mockito.any(Document.class), eq(Document.class))).thenReturn(mock(Document.class));
NearQuery query = NearQuery.near(new Point(1, 1)); NearQuery query = NearQuery.near(new Point(1, 1));
@ -461,8 +451,6 @@ public class MongoTemplateUnitTests extends MongoOperationsUnitTests {
MongoCursor cursor = mock(MongoCursor.class); MongoCursor cursor = mock(MongoCursor.class);
MapReduceIterable output = mock(MapReduceIterable.class); MapReduceIterable output = mock(MapReduceIterable.class);
when(output.limit(anyInt())).thenReturn(output); when(output.limit(anyInt())).thenReturn(output);
when(output.sort(Mockito.any(Document.class))).thenReturn(output);
when(output.filter(Mockito.any(Document.class))).thenReturn(output);
when(output.iterator()).thenReturn(cursor); when(output.iterator()).thenReturn(cursor);
when(cursor.hasNext()).thenReturn(false); when(cursor.hasNext()).thenReturn(false);

4
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/QueryCursorPreparerUnitTests.java

@ -57,12 +57,8 @@ public class QueryCursorPreparerUnitTests {
public void setUp() { public void setUp() {
when(factory.getExceptionTranslator()).thenReturn(exceptionTranslatorMock); when(factory.getExceptionTranslator()).thenReturn(exceptionTranslatorMock);
when(cursor.batchSize(anyInt())).thenReturn(cursor);
when(cursor.filter(any(Document.class))).thenReturn(cursor);
when(cursor.limit(anyInt())).thenReturn(cursor);
when(cursor.modifiers(any(Document.class))).thenReturn(cursor); when(cursor.modifiers(any(Document.class))).thenReturn(cursor);
when(cursor.noCursorTimeout(anyBoolean())).thenReturn(cursor); when(cursor.noCursorTimeout(anyBoolean())).thenReturn(cursor);
when(cursor.partial(anyBoolean())).thenReturn(cursor);
} }
@Test // DATAMONGO-185 @Test // DATAMONGO-185

4
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ReactiveMongoTemplateTests.java

@ -569,7 +569,7 @@ public class ReactiveMongoTemplateTests {
template.save(map, "maps").block(); template.save(map, "maps").block();
} }
@Test(expected = MappingException.class) // DATAMONGO-1444 @Test(expected = IllegalArgumentException.class) // DATAMONGO-1444
public void savesMongoPrimitiveObjectCorrectly() { public void savesMongoPrimitiveObjectCorrectly() {
template.save(new Object(), "collection").block(); template.save(new Object(), "collection").block();
} }
@ -588,7 +588,7 @@ public class ReactiveMongoTemplateTests {
assertThat(dbObject.containsKey("_id"), is(true)); assertThat(dbObject.containsKey("_id"), is(true));
} }
@Test(expected = InvalidDataAccessApiUsageException.class) // DATAMONGO-1444 @Test(expected = IllegalArgumentException.class) // DATAMONGO-1444
public void rejectsPlainObjectWithOutExplicitCollection() { public void rejectsPlainObjectWithOutExplicitCollection() {
Document dbObject = new Document("foo", "bar"); Document dbObject = new Document("foo", "bar");

10
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/DbRefMappingMongoConverterUnitTests.java

@ -31,7 +31,9 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObject;
import org.bson.BsonDocument;
import org.bson.Document; import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId; import org.bson.types.ObjectId;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -105,6 +107,8 @@ public class DbRefMappingMongoConverterUnitTests {
mapValDocument.put("_id", BigInteger.ONE); mapValDocument.put("_id", BigInteger.ONE);
DBRef dbRef = mock(DBRef.class); DBRef dbRef = mock(DBRef.class);
when(dbRef.getId()).thenReturn(BigInteger.ONE);
when(dbRef.getCollectionName()).thenReturn("collection-1");
if (MongoClientVersion.isMongo3Driver()) { if (MongoClientVersion.isMongo3Driver()) {
MongoDatabase dbMock = mock(MongoDatabase.class); MongoDatabase dbMock = mock(MongoDatabase.class);
@ -114,7 +118,7 @@ public class DbRefMappingMongoConverterUnitTests {
FindIterable fi = mock(FindIterable.class); FindIterable fi = mock(FindIterable.class);
when(fi.first()).thenReturn(mapValDocument); when(fi.first()).thenReturn(mapValDocument);
when(collectionMock.find(Matchers.any(Document.class))).thenReturn(fi); when(collectionMock.find(Mockito.any(Bson.class))).thenReturn(fi);
} else { } else {
when(dbRefResolver.fetch(dbRef)).thenReturn(mapValDocument); when(dbRefResolver.fetch(dbRef)).thenReturn(mapValDocument);
} }
@ -342,7 +346,6 @@ public class DbRefMappingMongoConverterUnitTests {
String id = "42"; String id = "42";
String value = "bubu"; String value = "bubu";
MappingMongoConverter converterSpy = spy(converter); MappingMongoConverter converterSpy = spy(converter);
doReturn(new Document("_id", id).append("value", value)).when(converterSpy).readRef((DBRef) any());
Document document = new Document(); Document document = new Document();
WithObjectMethodOverrideLazyDbRefs lazyDbRefs = new WithObjectMethodOverrideLazyDbRefs(); WithObjectMethodOverrideLazyDbRefs lazyDbRefs = new WithObjectMethodOverrideLazyDbRefs();
@ -368,7 +371,6 @@ public class DbRefMappingMongoConverterUnitTests {
String id = "42"; String id = "42";
String value = "bubu"; String value = "bubu";
MappingMongoConverter converterSpy = spy(converter); MappingMongoConverter converterSpy = spy(converter);
doReturn(new Document("_id", id).append("value", value)).when(converterSpy).readRef((DBRef) any());
Document document = new Document(); Document document = new Document();
WithObjectMethodOverrideLazyDbRefs lazyDbRefs = new WithObjectMethodOverrideLazyDbRefs(); WithObjectMethodOverrideLazyDbRefs lazyDbRefs = new WithObjectMethodOverrideLazyDbRefs();
@ -511,7 +513,7 @@ public class DbRefMappingMongoConverterUnitTests {
public void shouldNotTriggerResolvingOfLazyLoadedProxyWhenFinalizeMethodIsInvoked() throws Exception { public void shouldNotTriggerResolvingOfLazyLoadedProxyWhenFinalizeMethodIsInvoked() throws Exception {
MongoPersistentEntity<?> entity = mappingContext.getRequiredPersistentEntity(WithObjectMethodOverrideLazyDbRefs.class); MongoPersistentEntity<?> entity = mappingContext.getRequiredPersistentEntity(WithObjectMethodOverrideLazyDbRefs.class);
MongoPersistentProperty property = entity.getRequiredPersistentProperty("dbRefToConcreteTypeWithPropertyAccess"); MongoPersistentProperty property = entity.getRequiredPersistentProperty("dbRefToPlainObject");
String idValue = new ObjectId().toString(); String idValue = new ObjectId().toString();
DBRef dbRef = converter.toDBRef(new LazyDbRefTargetPropertyAccess(idValue), property); DBRef dbRef = converter.toDBRef(new LazyDbRefTargetPropertyAccess(idValue), property);

3
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/ReflectiveDBRefResolverUnitTests.java

@ -23,6 +23,7 @@ import static org.mockito.Mockito.*;
import static org.springframework.data.mongodb.util.MongoClientVersion.*; import static org.springframework.data.mongodb.util.MongoClientVersion.*;
import org.bson.Document; import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -56,7 +57,7 @@ public class ReflectiveDBRefResolverUnitTests {
when(dbRefMock.getId()).thenReturn("id-1"); when(dbRefMock.getId()).thenReturn("id-1");
when(dbFactoryMock.getDb()).thenReturn(dbMock); when(dbFactoryMock.getDb()).thenReturn(dbMock);
when(dbMock.getCollection(eq("collection-1"), eq(Document.class))).thenReturn(collectionMock); when(dbMock.getCollection(eq("collection-1"), eq(Document.class))).thenReturn(collectionMock);
when(collectionMock.find(any(org.bson.Document.class))).thenReturn(fi); when(collectionMock.find(any(Bson.class))).thenReturn(fi);
when(fi.first()).thenReturn(new Document("_id", "id-1")); when(fi.first()).thenReturn(new Document("_id", "id-1"));
} }

8
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/index/PathUnitTests.java

@ -39,12 +39,6 @@ public class PathUnitTests {
@Mock MongoPersistentEntity<?> entityMock; @Mock MongoPersistentEntity<?> entityMock;
@Before
@SuppressWarnings({ "rawtypes", "unchecked" })
public void setUp() {
when(entityMock.getType()).thenReturn((Class) Object.class);
}
@Test // DATAMONGO-962 @Test // DATAMONGO-962
public void shouldIdentifyCycleForOwnerOfSameTypeAndMatchingPath() { public void shouldIdentifyCycleForOwnerOfSameTypeAndMatchingPath() {
@ -59,7 +53,6 @@ public class PathUnitTests {
MongoPersistentProperty existing = createPersistentPropertyMock(entityMock, "foo"); MongoPersistentProperty existing = createPersistentPropertyMock(entityMock, "foo");
MongoPersistentEntity entityOfDifferentType = Mockito.mock(MongoPersistentEntity.class); MongoPersistentEntity entityOfDifferentType = Mockito.mock(MongoPersistentEntity.class);
when(entityOfDifferentType.getType()).thenReturn(String.class);
MongoPersistentProperty toBeVerified = createPersistentPropertyMock(entityOfDifferentType, "foo"); MongoPersistentProperty toBeVerified = createPersistentPropertyMock(entityOfDifferentType, "foo");
assertThat(new Path(existing, "foo.bar").cycles(toBeVerified, "foo.bar.bar"), is(false)); assertThat(new Path(existing, "foo.bar").cycles(toBeVerified, "foo.bar.bar"), is(false));
@ -77,7 +70,6 @@ public class PathUnitTests {
MongoPersistentProperty property = Mockito.mock(MongoPersistentProperty.class); MongoPersistentProperty property = Mockito.mock(MongoPersistentProperty.class);
when(property.getOwner()).thenReturn(owner); when(property.getOwner()).thenReturn(owner);
when(property.getFieldName()).thenReturn(fieldname);
return property; return property;
} }
} }

2
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/BasicMongoPersistentEntityUnitTests.java

@ -125,7 +125,6 @@ public class BasicMongoPersistentEntityUnitTests {
BasicMongoPersistentEntity<AnyDocument> entity = new BasicMongoPersistentEntity<AnyDocument>( BasicMongoPersistentEntity<AnyDocument> entity = new BasicMongoPersistentEntity<AnyDocument>(
ClassTypeInformation.from(AnyDocument.class)); ClassTypeInformation.from(AnyDocument.class));
when(propertyMock.isExplicitLanguageProperty()).thenReturn(false); when(propertyMock.isExplicitLanguageProperty()).thenReturn(false);
when(propertyMock.getActualType()).thenReturn((Class) Number.class);
entity.addPersistentProperty(propertyMock); entity.addPersistentProperty(propertyMock);
entity.verify(); entity.verify();
@ -197,7 +196,6 @@ public class BasicMongoPersistentEntityUnitTests {
when(propertyMock.isDbReference()).thenReturn(true); when(propertyMock.isDbReference()).thenReturn(true);
when(propertyMock.getDBRef()).thenReturn(dbRefMock); when(propertyMock.getDBRef()).thenReturn(dbRefMock);
when(dbRefMock.lazy()).thenReturn(false); when(dbRefMock.lazy()).thenReturn(false);
when(propertyMock.getActualType()).thenReturn((Class) Class.class);
entity.addPersistentProperty(propertyMock); entity.addPersistentProperty(propertyMock);
entity.verify(); entity.verify();

5
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/MongoMappingContextUnitTests.java

@ -22,6 +22,7 @@ import java.util.AbstractMap;
import java.util.Collections; import java.util.Collections;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@ -64,14 +65,14 @@ public class MongoMappingContextUnitTests {
public void doesNotReturnPersistentEntityForMongoSimpleType() { public void doesNotReturnPersistentEntityForMongoSimpleType() {
MongoMappingContext context = new MongoMappingContext(); MongoMappingContext context = new MongoMappingContext();
assertThat(context.getPersistentEntity(DBRef.class), is(nullValue())); assertThat(context.getPersistentEntity(DBRef.class), is(Optional.empty()));
} }
@Test // DATAMONGO-638 @Test // DATAMONGO-638
public void doesNotCreatePersistentEntityForAbstractMap() { public void doesNotCreatePersistentEntityForAbstractMap() {
MongoMappingContext context = new MongoMappingContext(); MongoMappingContext context = new MongoMappingContext();
assertThat(context.getPersistentEntity(AbstractMap.class), is(nullValue())); assertThat(context.getPersistentEntity(AbstractMap.class), is(Optional.empty()));
} }
@Test // DATAMONGO-607 @Test // DATAMONGO-607

8
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/IsQuery.java

@ -34,7 +34,7 @@ public class IsQuery<T extends Query> extends TypeSafeMatcher<T> {
protected Document sort; protected Document sort;
protected Document fields; protected Document fields;
private int skip; private long skip;
private int limit; private int limit;
private String hint; private String hint;
@ -52,7 +52,7 @@ public class IsQuery<T extends Query> extends TypeSafeMatcher<T> {
return this; return this;
} }
public IsQuery<T> skippig(int skip) { public IsQuery<T> skippig(long skip) {
this.skip = skip; this.skip = skip;
return this; return this;
} }
@ -121,7 +121,7 @@ public class IsQuery<T extends Query> extends TypeSafeMatcher<T> {
return false; return false;
} }
if (item.getSortObject() == null && !sort.isEmpty()) { if ((item.getSortObject() == null || item.getSortObject().isEmpty()) && !sort.isEmpty()) {
if (!new IsEqual<Document>(sort).matches(item.getSortObject())) { if (!new IsEqual<Document>(sort).matches(item.getSortObject())) {
return false; return false;
} }
@ -135,7 +135,7 @@ public class IsQuery<T extends Query> extends TypeSafeMatcher<T> {
return false; return false;
} }
if (!new IsEqual<Integer>(this.skip).matches(item.getSkip())) { if (!new IsEqual(this.skip).matches(item.getSkip())) {
return false; return false;
} }

2
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/IsTextQuery.java

@ -103,7 +103,7 @@ public class IsTextQuery<T extends Query> extends IsQuery<T> {
} }
@Override @Override
public IsQuery<T> skippig(int skip) { public IsQuery<T> skippig(long skip) {
super.skippig(skip); super.skippig(skip);
return this; return this;

16
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/NearQueryUnitTests.java

@ -89,20 +89,20 @@ public class NearQueryUnitTests {
Pageable pageable = new PageRequest(3, 5); Pageable pageable = new PageRequest(3, 5);
NearQuery query = NearQuery.near(new Point(1, 1)).with(pageable); NearQuery query = NearQuery.near(new Point(1, 1)).with(pageable);
assertThat(query.getSkip(), is(pageable.getPageNumber() * pageable.getPageSize())); assertThat(query.getSkip(), is((long)pageable.getPageNumber() * pageable.getPageSize()));
assertThat((Integer) query.toDocument().get("num"), is((pageable.getPageNumber() + 1) * pageable.getPageSize())); assertThat((Long) query.toDocument().get("num"), is((long)(pageable.getPageNumber() + 1) * pageable.getPageSize()));
} }
@Test // DATAMONGO-445 @Test // DATAMONGO-445
public void shouldTakeSkipAndLimitSettingsFromGivenQuery() { public void shouldTakeSkipAndLimitSettingsFromGivenQuery() {
int limit = 10; int limit = 10;
int skip = 5; long skip = 5;
NearQuery query = NearQuery.near(new Point(1, 1)) NearQuery query = NearQuery.near(new Point(1, 1))
.query(Query.query(Criteria.where("foo").is("bar")).limit(limit).skip(skip)); .query(Query.query(Criteria.where("foo").is("bar")).limit(limit).skip(skip));
assertThat(query.getSkip(), is(skip)); assertThat(query.getSkip(), is(skip));
assertThat((Integer) query.toDocument().get("num"), is(limit)); assertThat((Long) query.toDocument().get("num"), is((long)limit));
} }
@Test // DATAMONGO-445 @Test // DATAMONGO-445
@ -114,8 +114,8 @@ public class NearQueryUnitTests {
NearQuery query = NearQuery.near(new Point(1, 1)) NearQuery query = NearQuery.near(new Point(1, 1))
.query(Query.query(Criteria.where("foo").is("bar")).limit(limit).skip(skip)).with(pageable); .query(Query.query(Criteria.where("foo").is("bar")).limit(limit).skip(skip)).with(pageable);
assertThat(query.getSkip(), is(pageable.getPageNumber() * pageable.getPageSize())); assertThat(query.getSkip(), is((long)pageable.getPageNumber() * pageable.getPageSize()));
assertThat((Integer) query.toDocument().get("num"), is((pageable.getPageNumber() + 1) * pageable.getPageSize())); assertThat((Long) query.toDocument().get("num"), is((long)(pageable.getPageNumber() + 1) * pageable.getPageSize()));
} }
@Test // DATAMONGO-829 @Test // DATAMONGO-829
@ -133,11 +133,11 @@ public class NearQueryUnitTests {
@Test // DATAMONGO-829 @Test // DATAMONGO-829
public void numShouldNotBeAlteredByQueryWithoutPageable() { public void numShouldNotBeAlteredByQueryWithoutPageable() {
int num = 100; long num = 100;
NearQuery query = NearQuery.near(new Point(1, 2)); NearQuery query = NearQuery.near(new Point(1, 2));
query.num(num); query.num(num);
query.query(Query.query(Criteria.where("foo").is("bar"))); query.query(Query.query(Criteria.where("foo").is("bar")));
assertThat(DocumentTestUtils.getTypedValue(query.toDocument(), "num", Integer.class), is(num)); assertThat(DocumentTestUtils.getTypedValue(query.toDocument(), "num", Long.class), is(num));
} }
} }

2
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/TextQueryTests.java

@ -26,6 +26,7 @@ import static org.springframework.data.mongodb.core.query.Criteria.*;
import java.util.List; import java.util.List;
import lombok.ToString;
import org.bson.Document; import org.bson.Document;
import org.junit.Before; import org.junit.Before;
import org.junit.ClassRule; import org.junit.ClassRule;
@ -228,6 +229,7 @@ public class TextQueryTests extends AbstractIntegrationTests {
} }
@org.springframework.data.mongodb.core.mapping.Document(collection = "fullTextDoc") @org.springframework.data.mongodb.core.mapping.Document(collection = "fullTextDoc")
@ToString
static class FullTextDoc { static class FullTextDoc {
@Id String id; @Id String id;

3
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/AbstractPersonRepositoryIntegrationTests.java

@ -24,6 +24,7 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -109,7 +110,7 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
@Test @Test
public void findsPersonById() throws Exception { public void findsPersonById() throws Exception {
assertThat(repository.findOne(dave.getId().toString()), is(dave)); assertThat(repository.findOne(dave.getId().toString()), is(Optional.of(dave)));
} }
@Test @Test

3
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/ComplexIdRepositoryIntegrationTests.java

@ -21,6 +21,7 @@ import static org.junit.Assert.*;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Optional;
import org.hamcrest.Matchers; import org.hamcrest.Matchers;
import org.junit.Before; import org.junit.Before;
@ -106,7 +107,7 @@ public class ComplexIdRepositoryIntegrationTests {
repo.save(userWithId); repo.save(userWithId);
assertThat(repo.findOne(id), is(userWithId)); assertThat(repo.findOne(id), is(Optional.of(userWithId)));
} }
@Test // DATAMONGO-1078 @Test // DATAMONGO-1078

2
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/cdi/CdiExtensionIntegrationTests.java

@ -60,7 +60,7 @@ public class CdiExtensionIntegrationTests {
Person result = repository.save(person); Person result = repository.save(person);
assertThat(result, is(notNullValue())); assertThat(result, is(notNullValue()));
assertThat(repository.findOne(person.getId()).getId(), is(result.getId())); assertThat(repository.findOne(person.getId()).get().getId(), is(result.getId()));
} }
@Test // DATAMONGO-1017 @Test // DATAMONGO-1017

4
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/cdi/CdiPersonRepository.java

@ -15,6 +15,8 @@
*/ */
package org.springframework.data.mongodb.repository.cdi; package org.springframework.data.mongodb.repository.cdi;
import java.util.Optional;
import org.springframework.data.mongodb.repository.Person; import org.springframework.data.mongodb.repository.Person;
import org.springframework.data.repository.Repository; import org.springframework.data.repository.Repository;
@ -24,5 +26,5 @@ public interface CdiPersonRepository extends Repository<Person, String> {
Person save(Person person); Person save(Person person);
Person findOne(String id); Optional<Person> findOne(String id);
} }

12
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/query/AbstractMongoQueryUnitTests.java

@ -81,7 +81,8 @@ public class AbstractMongoQueryUnitTests {
public void setUp() { public void setUp() {
doReturn("persons").when(persitentEntityMock).getCollection(); doReturn("persons").when(persitentEntityMock).getCollection();
doReturn(persitentEntityMock).when(mappingContextMock).getPersistentEntity(Matchers.any(Class.class)); doReturn(Optional.of(persitentEntityMock)).when(mappingContextMock).getPersistentEntity(Mockito.any(Class.class));
doReturn(persitentEntityMock).when(mappingContextMock).getRequiredPersistentEntity(Mockito.any(Class.class));
doReturn(Person.class).when(persitentEntityMock).getType(); doReturn(Person.class).when(persitentEntityMock).getType();
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mock(MongoDbFactory.class)); DbRefResolver dbRefResolver = new DefaultDbRefResolver(mock(MongoDbFactory.class));
@ -106,12 +107,9 @@ public class AbstractMongoQueryUnitTests {
@Test // DATAMONGO-566, DATAMONGO-1040 @Test // DATAMONGO-566, DATAMONGO-1040
public void testDeleteExecutionLoadsListOfRemovedDocumentsWhenReturnTypeIsCollectionLike() { public void testDeleteExecutionLoadsListOfRemovedDocumentsWhenReturnTypeIsCollectionLike() {
when(mongoOperationsMock.find(Matchers.any(Query.class), Matchers.any(Class.class), Matchers.anyString()))
.thenReturn(Arrays.asList(new Person(new ObjectId(new Date()), "bar")));
createQueryForMethod("deleteByLastname", String.class).setDeleteQuery(true).execute(new Object[] { "booh" }); createQueryForMethod("deleteByLastname", String.class).setDeleteQuery(true).execute(new Object[] { "booh" });
verify(mongoOperationsMock, times(1)).findAllAndRemove(Matchers.any(Query.class), eq(Person.class), eq("persons")); verify(mongoOperationsMock, times(1)).findAllAndRemove(Mockito.any(Query.class), eq(Person.class), eq("persons"));
} }
@Test // DATAMONGO-566 @Test // DATAMONGO-566
@ -200,8 +198,8 @@ public class AbstractMongoQueryUnitTests {
verify(mongoOperationsMock, times(2)).find(captor.capture(), eq(Person.class), eq("persons")); verify(mongoOperationsMock, times(2)).find(captor.capture(), eq(Person.class), eq("persons"));
assertThat(captor.getAllValues().get(0).getSkip(), is(0)); assertThat(captor.getAllValues().get(0).getSkip(), is(0L));
assertThat(captor.getAllValues().get(1).getSkip(), is(10)); assertThat(captor.getAllValues().get(1).getSkip(), is(10L));
} }
@Test // DATAMONGO-1057 @Test // DATAMONGO-1057

4
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/query/ReactiveMongoQueryExecutionUnitTests.java

@ -70,7 +70,7 @@ public class ReactiveMongoQueryExecutionUnitTests {
NearQuery nearQuery = queryArgumentCaptor.getValue(); NearQuery nearQuery = queryArgumentCaptor.getValue();
assertThat(nearQuery.toDocument().get("near"), is(equalTo(Arrays.asList(1d, 2d)))); assertThat(nearQuery.toDocument().get("near"), is(equalTo(Arrays.asList(1d, 2d))));
assertThat(nearQuery.getSkip(), is(10)); assertThat(nearQuery.getSkip(), is(10L));
assertThat(nearQuery.getMinDistance(), is(equalTo(new Distance(10)))); assertThat(nearQuery.getMinDistance(), is(equalTo(new Distance(10))));
assertThat(nearQuery.getMaxDistance(), is(equalTo(new Distance(15)))); assertThat(nearQuery.getMaxDistance(), is(equalTo(new Distance(15))));
} }
@ -91,7 +91,7 @@ public class ReactiveMongoQueryExecutionUnitTests {
NearQuery nearQuery = queryArgumentCaptor.getValue(); NearQuery nearQuery = queryArgumentCaptor.getValue();
assertThat(nearQuery.toDocument().get("near"), is(equalTo(Arrays.asList(1d, 2d)))); assertThat(nearQuery.toDocument().get("near"), is(equalTo(Arrays.asList(1d, 2d))));
assertThat(nearQuery.getSkip(), is(0)); assertThat(nearQuery.getSkip(), is(0L));
assertThat(nearQuery.getMinDistance(), is(nullValue())); assertThat(nearQuery.getMinDistance(), is(nullValue()));
assertThat(nearQuery.getMaxDistance(), is(nullValue())); assertThat(nearQuery.getMaxDistance(), is(nullValue()));
} }

3
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/query/ReactiveStringBasedMongoQueryUnitTests.java

@ -69,9 +69,6 @@ public class ReactiveStringBasedMongoQueryUnitTests {
@Before @Before
public void setUp() { public void setUp() {
when(operations.getConverter()).thenReturn(converter);
this.converter = new MappingMongoConverter(factory, new MongoMappingContext()); this.converter = new MappingMongoConverter(factory, new MongoMappingContext());
} }

2
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/query/StringBasedMongoQueryUnitTests.java

@ -74,8 +74,6 @@ public class StringBasedMongoQueryUnitTests {
@Before @Before
public void setUp() { public void setUp() {
when(operations.getConverter()).thenReturn(converter);
this.converter = new MappingMongoConverter(factory, new MongoMappingContext()); this.converter = new MappingMongoConverter(factory, new MongoMappingContext());
} }

4
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/support/MongoRepositoryFactoryUnitTests.java

@ -68,7 +68,7 @@ public class MongoRepositoryFactoryUnitTests {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void usesMappingMongoEntityInformationIfMappingContextSet() { public void usesMappingMongoEntityInformationIfMappingContextSet() {
when(mappingContext.getPersistentEntity(Person.class)).thenReturn(Optional.of(entity)); when(mappingContext.getRequiredPersistentEntity(Person.class)).thenReturn(entity);
when(entity.getType()).thenReturn(Person.class); when(entity.getType()).thenReturn(Person.class);
MongoRepositoryFactory factory = new MongoRepositoryFactory(template); MongoRepositoryFactory factory = new MongoRepositoryFactory(template);
@ -80,7 +80,7 @@ public class MongoRepositoryFactoryUnitTests {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void createsRepositoryWithIdTypeLong() { public void createsRepositoryWithIdTypeLong() {
when(mappingContext.getPersistentEntity(Person.class)).thenReturn(Optional.of(entity)); when(mappingContext.getRequiredPersistentEntity(Person.class)).thenReturn(entity);
when(entity.getType()).thenReturn(Person.class); when(entity.getType()).thenReturn(Person.class);
MongoRepositoryFactory factory = new MongoRepositoryFactory(template); MongoRepositoryFactory factory = new MongoRepositoryFactory(template);

Loading…
Cancel
Save