Skip to content

Commit

Permalink
#1368 fix "Duplicate key error" (#1369)
Browse files Browse the repository at this point in the history
... when a custom faker has multiple methods with the same return type.
  • Loading branch information
asolntsev authored Oct 5, 2024
1 parent 09c0693 commit 41b5693
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ private static synchronized Map<String, Method> scanMethodsByName(Class<?> clazz
private static synchronized Map<String, Method> scanMethodsByReturnType(Class<?> clazz) {
return Stream.of(clazz.getMethods())
.filter(ObjectMethods::isUseful)
.collect(toMap(method -> method.getReturnType().getSimpleName(), method -> method));
.collect(toMap(method -> method.getReturnType().getSimpleName(), method -> method, ObjectMethods::chooseFirstByAlphabet));
}

private static Method chooseFirstByAlphabet(Method m1, Method m2) {
return m1.getName().compareTo(m2.getName()) < 0 ? m1 : m2;
}

/**
Expand Down
11 changes: 11 additions & 0 deletions src/test/java/net/datafaker/providers/base/ObjectMethodsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ void methodByReturnType() {
assertThat((CharSequence) executeMethodByReturnType(personName, "CharSequence")).isEqualTo("Smith");
}

@Test
void multipleMethodsWithSameReturnType() {
assertThat((Float) executeMethodByReturnType(personName, "float")).isEqualTo(90.0f);
}

private static class Person {
public Age age() {
return new Age();
Expand All @@ -50,5 +55,11 @@ public String firstName() {
public CharSequence lastName() {
return "Smith";
}
public float weight() {
return 90.0f;
}
public float width() {
return 60.0f;
}
}
}

0 comments on commit 41b5693

Please sign in to comment.