Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tests for enum constant toString() reading #2080

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
51 changes: 48 additions & 3 deletions gson/src/test/java/com/google/gson/functional/EnumTest.java
Expand Up @@ -37,6 +37,7 @@
import java.util.Map;
import java.util.Set;
import junit.framework.TestCase;

/**
* Functional tests for Java 5.0 enums.
*
Expand Down Expand Up @@ -174,7 +175,7 @@ public void testEnumMap() throws Exception {
assertEquals(expectedMap, actualMap);
}

public enum Roshambo {
private enum Roshambo {
ROCK {
@Override Roshambo defeats() {
return SCISSORS;
Expand Down Expand Up @@ -206,7 +207,7 @@ private static class MyEnumTypeAdapter
}
}

public enum Gender {
private enum Gender {
@SerializedName("boy")
MALE,

Expand All @@ -217,9 +218,10 @@ public enum Gender {
public void testEnumClassWithFields() {
assertEquals("\"RED\"", gson.toJson(Color.RED));
assertEquals("red", gson.fromJson("RED", Color.class).value);
assertEquals(2, gson.fromJson("BLUE", Color.class).index);
}

public enum Color {
private enum Color {
RED("red", 1), BLUE("blue", 2), GREEN("green", 3);
String value;
int index;
Expand All @@ -228,4 +230,47 @@ private Color(String value, int index) {
this.index = index;
}
}

public void testEnumToStringRead() {
// Should still be able to read constant name
assertEquals(CustomToString.A, gson.fromJson("\"A\"", CustomToString.class));
// Should be able to read toString() value
assertEquals(CustomToString.A, gson.fromJson("\"test\"", CustomToString.class));

assertNull(gson.fromJson("\"other\"", CustomToString.class));
}

private enum CustomToString {
A;

@Override
public String toString() {
return "test";
}
}

/**
* Test that enum constant names have higher precedence than {@code toString()}
* result.
*/
public void testEnumToStringReadInterchanged() {
assertEquals(InterchangedToString.A, gson.fromJson("\"A\"", InterchangedToString.class));
assertEquals(InterchangedToString.B, gson.fromJson("\"B\"", InterchangedToString.class));
}

private enum InterchangedToString {
A("B"),
B("A");

private final String toString;

InterchangedToString(String toString) {
this.toString = toString;
}

@Override
public String toString() {
return toString;
}
}
}