added tests for using intercept in fields and lists. These tests are currently failing.

This commit is contained in:
Inderjeet Singh 2012-10-11 20:29:40 +00:00
parent c25278b4d6
commit 714ac8e643

View File

@ -15,11 +15,15 @@
*/ */
package com.google.gson.functional; package com.google.gson.functional;
import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.internal.alpha.Intercept; import com.google.gson.internal.alpha.Intercept;
import com.google.gson.internal.alpha.JsonPostDeserializer; import com.google.gson.internal.alpha.JsonPostDeserializer;
import com.google.gson.reflect.TypeToken;
/** /**
* Unit tests for {@link Intercept} and {@link JsonPostDeserializer}. * Unit tests for {@link Intercept} and {@link JsonPostDeserializer}.
@ -36,29 +40,48 @@ public final class InterceptorTest extends TestCase {
this.gson = new Gson(); this.gson = new Gson();
} }
public void testPostDeserialize() { public void testExceptionsPropagated() {
MyObject target = gson.fromJson("{}", MyObject.class); try {
assertEquals(MyObject.DEFAULT_VALUE, target.value); gson.fromJson("{}", User.class);
assertEquals(MyObject.DEFAULT_MESSAGE, target.message); fail();
} catch (JsonParseException expected) {}
} }
@Intercept(postDeserialize = MyObjectInterceptor.class) public void testPostDeserializeTopLevelClass() {
private static final class MyObject { User user = gson.fromJson("{name:'bob',password:'pwd'}", User.class);
static final int DEFAULT_VALUE = 10; assertEquals(User.DEFAULT_EMAIL, user.email);
static final String DEFAULT_MESSAGE = "hello";
int value = 0;
String message = null;
} }
private static final class MyObjectInterceptor implements JsonPostDeserializer<MyObject> { public void testPostDeserializeList() {
public void postDeserialize(MyObject o) { List<User> list = gson.fromJson("[{name:'bob',password:'pwd'}]", new TypeToken<List<User>>(){}.getType());
if (o.value == 0) { User user = list.get(0);
o.value = MyObject.DEFAULT_VALUE; assertEquals(User.DEFAULT_EMAIL, user.email);
} }
if (o.message == null) {
o.message = MyObject.DEFAULT_MESSAGE; public void testPostDeserializeField() {
UserGroup userGroup = gson.fromJson("{user:{name:'bob',password:'pwd'}}", UserGroup.class);
assertEquals(User.DEFAULT_EMAIL, userGroup.user.email);
}
private static final class UserGroup {
User user;
String city;
}
@Intercept(postDeserialize = UserValidator.class)
private static final class User {
static final String DEFAULT_EMAIL = "invalid@invalid.com";
String name;
String password;
String email;
}
private static final class UserValidator implements JsonPostDeserializer<User> {
public void postDeserialize(User user) {
if (user.name == null || user.password == null) {
throw new JsonParseException("name and password are required fields.");
} }
if (user.email == null) user.email = User.DEFAULT_EMAIL;
} }
} }
} }