Skip to content

Commit

Permalink
Don't assert exact exception type when StackOverflowError is thrown (#…
Browse files Browse the repository at this point in the history
…2815)

* Don't assert exact exception type when StackOverflowError is thrown

* Check for StackOverflowError as root cause
  • Loading branch information
Marcono1234 authored Feb 23, 2025
1 parent c395dd1 commit 0e591c2
Showing 1 changed file with 13 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import com.google.common.base.Throwables;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
Expand All @@ -30,6 +31,7 @@
import java.util.Collection;
import org.junit.Before;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;

/**
* Functional tests related to circular reference detection and error reporting.
Expand All @@ -52,7 +54,7 @@ public void testCircularSerialization() {
a.children.add(b);
b.children.add(a);
// Circular types should not get printed
assertThrows(StackOverflowError.class, () -> gson.toJson(a));
assertThrowsStackOverflow(() -> gson.toJson(a));
}

@Test
Expand All @@ -70,7 +72,7 @@ public void testSelfReferenceArrayFieldSerialization() {
objA.children = new ClassWithSelfReferenceArray[] {objA};

// Circular reference to self can not be serialized
assertThrows(StackOverflowError.class, () -> gson.toJson(objA));
assertThrowsStackOverflow(() -> gson.toJson(objA));
}

@Test
Expand All @@ -96,7 +98,15 @@ public JsonElement serialize(
.create();

// Circular reference to self can not be serialized
assertThrows(StackOverflowError.class, () -> gson.toJson(obj));
assertThrowsStackOverflow(() -> gson.toJson(obj));
}

/** Asserts that a {@link StackOverflowError} is thrown. */
private static void assertThrowsStackOverflow(ThrowingRunnable runnable) {
// Obtain the root cause because the StackOverflowError might occur in JDK code, and that might
// wrap it in another exception class, for example InternalError
Throwable t = assertThrows(Throwable.class, runnable);
assertThat(Throwables.getRootCause(t)).isInstanceOf(StackOverflowError.class);
}

@Test
Expand Down

0 comments on commit 0e591c2

Please sign in to comment.