From b4d51db776325cd0da58d96d973175dc1b86b256 Mon Sep 17 00:00:00 2001 From: Jesse Wilson Date: Mon, 29 Oct 2012 16:30:33 +0000 Subject: [PATCH] Add a test case for a problem reported on the group. https://groups.google.com/d/topic/google-gson/EBmOCa8kJPE/discussion --- .../com/google/gson/GsonTypeAdapterTest.java | 45 ++++++++++++++++++- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java b/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java index b7322bf4..922cecc4 100644 --- a/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java +++ b/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java @@ -16,12 +16,11 @@ package com.google.gson; -import junit.framework.TestCase; - import java.lang.reflect.Type; import java.math.BigInteger; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; +import junit.framework.TestCase; /** * Contains numerous tests involving registered type converters with a Gson instance. @@ -105,4 +104,46 @@ public class GsonTypeAdapterTest extends TestCase { return new AtomicInteger(--intValue); } } + + static abstract class Abstract { + String a; + } + + static class Concrete extends Abstract { + String b; + } + + // https://groups.google.com/d/topic/google-gson/EBmOCa8kJPE/discussion + public void testDeserializerForAbstractClass() { + Concrete instance = new Concrete(); + instance.a = "android"; + instance.b = "beep"; + assertSerialized("{\"a\":\"android\"}", Abstract.class, true, true, instance); + assertSerialized("{\"a\":\"android\"}", Abstract.class, true, false, instance); + assertSerialized("{\"a\":\"android\"}", Abstract.class, false, true, instance); + assertSerialized("{\"a\":\"android\"}", Abstract.class, false, false, instance); + assertSerialized("{\"b\":\"beep\",\"a\":\"android\"}", Concrete.class, true, true, instance); + assertSerialized("{\"b\":\"beep\",\"a\":\"android\"}", Concrete.class, true, false, instance); + assertSerialized("{\"b\":\"beep\",\"a\":\"android\"}", Concrete.class, false, true, instance); + assertSerialized("{\"b\":\"beep\",\"a\":\"android\"}", Concrete.class, false, false, instance); + } + + private void assertSerialized(String expected, Class instanceType, boolean registerAbstractDeserializer, + boolean registerAbstractHierarchyDeserializer, Object instance) { + JsonDeserializer deserializer = new JsonDeserializer() { + public Abstract deserialize(JsonElement json, Type typeOfT, + JsonDeserializationContext context) throws JsonParseException { + throw new AssertionError(); + } + }; + GsonBuilder builder = new GsonBuilder(); + if (registerAbstractDeserializer) { + builder.registerTypeAdapter(Abstract.class, deserializer); + } + if (registerAbstractHierarchyDeserializer) { + builder.registerTypeHierarchyAdapter(Abstract.class, deserializer); + } + Gson gson = builder.create(); + assertEquals(expected, gson.toJson(instance, instanceType)); + } }