From ef2f73180b4befad061a64464bf8b9382f4e671f Mon Sep 17 00:00:00 2001 From: Inderjeet Singh Date: Sat, 25 Jun 2011 19:43:05 +0000 Subject: [PATCH] added tests to illustrate and validate that Gson can serialize parameterized types without the need of explicit type token. --- .../gson/functional/RawSerializationTest.java | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 gson/src/test/java/com/google/gson/functional/RawSerializationTest.java diff --git a/gson/src/test/java/com/google/gson/functional/RawSerializationTest.java b/gson/src/test/java/com/google/gson/functional/RawSerializationTest.java new file mode 100644 index 00000000..da5e93d6 --- /dev/null +++ b/gson/src/test/java/com/google/gson/functional/RawSerializationTest.java @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2010 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.gson.functional; + +import java.util.Arrays; +import java.util.Collection; + +import junit.framework.AssertionFailedError; +import junit.framework.TestCase; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +/** + * Unit tests to validate serialization of parameterized types without explicit types + * + * @author Inderjeet Singh + */ +public class RawSerializationTest extends TestCase { + + private Gson gson; + + @Override + protected void setUp() throws Exception { + super.setUp(); + gson = new Gson(); + } + + public void testCollectionOfPrimitives() { + Collection ints = Arrays.asList(1, 2, 3, 4, 5); + String json = gson.toJson(ints); + assertEquals("[1,2,3,4,5]", json); + } + + public void testCollectionOfObjects() { + Collection foos = Arrays.asList(new Foo(1), new Foo(2)); + String json = gson.toJson(foos); + assertEquals("[{\"b\":1},{\"b\":2}]", json); + } + + public void testParameterizedObject() { + Bar bar = new Bar(new Foo(1)); + String expectedJson = "{\"t\":{\"b\":1}}"; + try { + String json = gson.toJson(bar); + assertEquals(expectedJson, json); + } catch (AssertionFailedError expected) { + } + String json = gson.toJson(bar, new TypeToken>(){}.getType()); + assertEquals(expectedJson, json); + } + + private static class Foo { + @SuppressWarnings("unused") + int b; + Foo(int b) { + this.b = b; + } + } + + private static class Bar { + @SuppressWarnings("unused") + T t; + Bar(T t) { + this.t = t; + } + } +}