Skip to content

Instantly share code, notes, and snippets.

@AdelinGhanaem
Created November 14, 2012 14:27
Show Gist options
  • Save AdelinGhanaem/4072405 to your computer and use it in GitHub Desktop.
Save AdelinGhanaem/4072405 to your computer and use it in GitHub Desktop.
Testing sitebricks
/**
* @author Adelin Ghanayem [email protected]
*/
public class SitebricksReplyAssertion {
public static <T> void assertIsRepliedWith(Reply<T> reply, T expected) {
assertFieldValue("entity", reply, expected);
}
public static <T> void assertThatReplyStatusIs(Reply<T> reply, int expected) {
assertFieldValue("status", reply, expected);
}
private static <T> void assertFieldValue(String fieldName, Reply reply, T expected) {
Field field = null;
try {
field = reply.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
T actual = (T) field.get(reply);
assert actual != null;
assertThat(actual, is(equalTo(expected)));
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
@jwmach1
Copy link

jwmach1 commented Nov 14, 2012

having a finally block that returns field.setAccessible to the prior value is a good idea.

@AdelinGhanaem
Copy link
Author

would you explain in more details, what for is the final field ?

@mgenov
Copy link

mgenov commented Dec 12, 2012

Hamcrest could improve the way you read your test. Here is small example that is based on your snippet:

 @Test
  public void requestingSingleServiceIsStoredInTheDatastore() {
    final Datastore datastore = context.mock(Datastore.class);
    final Service service = newService("Service1");
    final List<Service> services = listOf(service);

    context.checking(new Expectations() {{
      oneOf(datastore).save(service);
    }});

    ServiceEndpoint endpoint = new ServiceEndpoint(datastore);

    Reply<?> reply = endpoint.provisionService(newRequest(services));

    assertThat(reply, isOk());
    assertThat(reply, containsValue("SUCCESS"));
  }

@AdelinGhanaem
Copy link
Author

This is better I guess.

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