Skip to content

Commit 3ca564b

Browse files
committed
#449 Register error for duplicate key in Map property type
1 parent 730c5a5 commit 3ca564b

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

src/main/java/ch/jalu/configme/properties/types/MapPropertyType.java

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88
import java.util.Map;
99

1010
/**
11-
* Property types for maps with strings as keys and any value type. The produced maps keep insertion order (as seen
12-
* in the property resource). Maps produced by this type never have a null key or null value.
11+
* Property types for maps with strings as keys and any value type. The produced maps keep insertion order (as given
12+
* in the property resource). Maps produced by this type never have a null key or a null value.
1313
*
1414
* @param <V> the type of values in the map
1515
*/
@@ -40,7 +40,10 @@ public MapPropertyType(@NotNull PropertyType<V> valueType) {
4040
V value = valueType.convert(entry.getValue(), errorRecorder);
4141

4242
if (key != null && value != null) {
43-
map.put(key, value);
43+
V previous = map.put(key, value);
44+
if (previous != null) {
45+
errorRecorder.setHasError("Duplicate key detected: '" + key + "'");
46+
}
4447
} else {
4548
errorRecorder.setHasError("Key or value could not be converted for key '" + entry.getKey() + "'");
4649
}
@@ -57,7 +60,7 @@ public MapPropertyType(@NotNull PropertyType<V> valueType) {
5760
return exportMap;
5861
}
5962

60-
public @NotNull PropertyType<V> getValueType() {
63+
public final @NotNull PropertyType<V> getValueType() {
6164
return valueType;
6265
}
6366

src/test/java/ch/jalu/configme/properties/types/MapPropertyTypeTest.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,28 @@ void shouldBuildMapAndSkipNullKey() {
8585
assertThat(errorRecorder.isFullyValid(), equalTo(false));
8686
}
8787

88+
@Test
89+
void shouldRegisterErrorOnDuplicateKey() {
90+
// given
91+
MapPropertyType<TestEnum> mapType = new MapPropertyType<>(EnumPropertyType.of(TestEnum.class));
92+
ConvertErrorRecorder errorRecorder = new ConvertErrorRecorder();
93+
94+
Map<Object, String> inputMap = new LinkedHashMap<>();
95+
inputMap.put(1, "SECOND");
96+
inputMap.put("3", "THIRD");
97+
inputMap.put(3, "FIRST");
98+
99+
// when
100+
Map<String, TestEnum> result = mapType.convert(inputMap, errorRecorder);
101+
102+
// then
103+
assertThat(result, instanceOf(LinkedHashMap.class));
104+
assertThat(result.keySet(), contains("1", "3"));
105+
assertThat(result.get("1"), equalTo(TestEnum.SECOND));
106+
assertThat(result.get("3"), equalTo(TestEnum.FIRST));
107+
assertThat(errorRecorder.isFullyValid(), equalTo(false));
108+
}
109+
88110
@Test
89111
void shouldExportMap() {
90112
// given

0 commit comments

Comments
 (0)