Skip to content

Instantly share code, notes, and snippets.

@chids
Created May 22, 2012 14:20
Show Gist options
  • Save chids/2769366 to your computer and use it in GitHub Desktop.
Save chids/2769366 to your computer and use it in GitHub Desktop.
Dropwizard representation round trip test (instance -> json -> instance)
public static <T> void jsonRoundTripTest(final T instance) throws Exception {
final String clazz = instance.getClass().getName();
final String fixtureName = instance.getClass().getSimpleName().toLowerCase();
final String fixture = jsonFixture("fixtures/" + fixtureName + ".json");
assertThat(clazz + " bad json,",
asJson(instance),
is(fixture));
T deserialized;
try {
deserialized = fromJson(fixture, (Class<T>)instance.getClass());
}
catch(final Exception e) {
throw new Exception("Can't deserialize:\n" + asJson(instance), e);
}
assertThat(clazz + " bad equals,",
deserialized,
is(instance));
assertEquals(clazz + " bad hashcode,",
deserialized.hashCode(),
instance.hashCode());
}
@andreisavu
Copy link

Cool snippet! Something like this should probably ship as part of dropwizard-testing.

@chids
Copy link
Author

chids commented Aug 1, 2012

@andreisavu
Copy link

thanks!

@chids
Copy link
Author

chids commented Aug 7, 2012

@andreisavu FYI: Coda didn't agree on it being a good thing to include, but on the other hand it's a small enough code snippet to copy-n-paste into your own codebase.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment