Skip to content

Commit f814b1e

Browse files
committed
DATAMONGO-1128 - Added test cases to validate Optional mapping.
Added test cases to make sure Optional instances are handled correctly and the converters are actually applied to the nested value.
1 parent f3d2ae3 commit f814b1e

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

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

+45
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
*/
1616
package org.springframework.data.mongodb.core.convert;
1717

18+
import static java.time.ZoneId.*;
1819
import static org.hamcrest.Matchers.*;
1920
import static org.junit.Assert.*;
2021
import static org.mockito.Mockito.*;
@@ -36,6 +37,7 @@
3637
import java.util.List;
3738
import java.util.Locale;
3839
import java.util.Map;
40+
import java.util.Optional;
3941
import java.util.Set;
4042
import java.util.SortedMap;
4143
import java.util.TreeMap;
@@ -1962,6 +1964,43 @@ public void convertsJava8DateTimeTypesToDateAndBack() {
19621964
assertThat(converter.read(TypeWithLocalDateTime.class, result).date, is(reference));
19631965
}
19641966

1967+
/**
1968+
* @see DATAMONGO-1128
1969+
*/
1970+
@Test
1971+
public void writesOptionalsCorrectly() {
1972+
1973+
TypeWithOptional type = new TypeWithOptional();
1974+
type.localDateTime = Optional.of(LocalDateTime.now());
1975+
1976+
DBObject result = new BasicDBObject();
1977+
1978+
converter.write(type, result);
1979+
1980+
assertThat(getAsDBObject(result, "string"), is((DBObject) new BasicDBObject()));
1981+
1982+
DBObject localDateTime = getAsDBObject(result, "localDateTime");
1983+
assertThat(localDateTime.get("value"), is(instanceOf(Date.class)));
1984+
}
1985+
1986+
/**
1987+
* @see DATAMONGO-1128
1988+
*/
1989+
@Test
1990+
public void readsOptionalsCorrectly() {
1991+
1992+
LocalDateTime now = LocalDateTime.now();
1993+
Date reference = Date.from(now.atZone(systemDefault()).toInstant());
1994+
1995+
BasicDBObject optionalOfLocalDateTime = new BasicDBObject("value", reference);
1996+
DBObject result = new BasicDBObject("localDateTime", optionalOfLocalDateTime);
1997+
1998+
TypeWithOptional read = converter.read(TypeWithOptional.class, result);
1999+
2000+
assertThat(read.string, is(Optional.<String> empty()));
2001+
assertThat(read.localDateTime, is(Optional.of(now)));
2002+
}
2003+
19652004
static class GenericType<T> {
19662005
T content;
19672006
}
@@ -2258,4 +2297,10 @@ static class TypeWithLocalDateTime {
22582297
this.date = LocalDateTime.now();
22592298
}
22602299
}
2300+
2301+
static class TypeWithOptional {
2302+
2303+
Optional<String> string = Optional.empty();
2304+
Optional<LocalDateTime> localDateTime = Optional.empty();
2305+
}
22612306
}

0 commit comments

Comments
 (0)