Skip to content

Commit

Permalink
Improve GsonTest.testGetAdapter_Concurrency (#2177)
Browse files Browse the repository at this point in the history
Makes the test implementation more reliable to prevent flaws in the test
setup causing spurious test success.
  • Loading branch information
Marcono1234 authored Aug 19, 2022
1 parent 5e1005e commit 18b9ba4
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions gson/src/test/java/com/google/gson/GsonTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import junit.framework.TestCase;

Expand Down Expand Up @@ -102,6 +103,17 @@ public void testGetAdapter_Null() {
}

public void testGetAdapter_Concurrency() {
class DummyAdapter<T> extends TypeAdapter<T> {
@Override public void write(JsonWriter out, T value) throws IOException {
throw new AssertionError("not needed for test");
}

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

final AtomicInteger adapterInstancesCreated = new AtomicInteger(0);
final AtomicReference<TypeAdapter<?>> threadAdapter = new AtomicReference<>();
final Class<?> requestedType = Number.class;

Expand Down Expand Up @@ -130,24 +142,15 @@ public void testGetAdapter_Concurrency() {
}

// Create a new dummy adapter instance

@SuppressWarnings("unchecked")
TypeAdapter<T> r = (TypeAdapter<T>) new TypeAdapter<Number>() {
@Override public void write(JsonWriter out, Number value) throws IOException {
throw new AssertionError("not needed for test");
}

@Override public Number read(JsonReader in) throws IOException {
throw new AssertionError("not needed for test");
}
};
return r;
adapterInstancesCreated.incrementAndGet();
return new DummyAdapter<>();
}
})
.create();

TypeAdapter<?> adapter = gson.getAdapter(requestedType);
assertNotNull(adapter);
assertTrue(adapter instanceof DummyAdapter);
assertEquals(2, adapterInstancesCreated.get());
// Should be the same adapter instance the concurrent thread received
assertSame(threadAdapter.get(), adapter);
}
Expand Down

0 comments on commit 18b9ba4

Please sign in to comment.