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

Fix TypeAdapter.toJson throwing AssertionError for custom IOException #2172

Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 1 addition & 1 deletion gson/src/main/java/com/google/gson/TypeAdapter.java
Expand Up @@ -216,7 +216,7 @@ public final String toJson(T value) {
try {
toJson(stringWriter, value);
} catch (IOException e) {
throw new AssertionError(e); // No I/O writing to a StringWriter.
throw new JsonIOException(e);
eamonnmcmanus marked this conversation as resolved.
Show resolved Hide resolved
}
return stringWriter.toString();
}
Expand Down
33 changes: 33 additions & 0 deletions gson/src/test/java/com/google/gson/TypeAdapterTest.java
Expand Up @@ -2,6 +2,7 @@

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
Expand All @@ -26,6 +27,38 @@ public void testNullSafe() throws IOException {
assertNull(adapter.fromJson("null"));
}

/**
* Tests behavior when {@link TypeAdapter#write(JsonWriter, Object)} manually throws
* {@link IOException} which is not caused by writer usage.
*/
@Test
public void testToJson_ThrowingIOException() {
final IOException exception = new IOException("test");
TypeAdapter<Integer> adapter = new TypeAdapter<Integer>() {
@Override public void write(JsonWriter out, Integer value) throws IOException {
throw exception;
}

@Override public Integer read(JsonReader in) throws IOException {
throw new AssertionError("not needed by this test");
}
};

try {
adapter.toJson(1);
fail();
} catch (JsonIOException e) {
assertEquals(exception, e.getCause());
}

try {
adapter.toJsonTree(1);
fail();
} catch (JsonIOException e) {
assertEquals(exception, e.getCause());
}
}

private static final TypeAdapter<String> adapter = new TypeAdapter<String>() {
@Override public void write(JsonWriter out, String value) throws IOException {
out.value(value);
Expand Down