Skip to content

Instantly share code, notes, and snippets.

@mgenov
Created December 8, 2016 12:15
Show Gist options
  • Save mgenov/1a1a831678437ed9d87a6cc6ebd45bac to your computer and use it in GitHub Desktop.
Save mgenov/1a1a831678437ed9d87a6cc6ebd45bac to your computer and use it in GitHub Desktop.
Sitebricks Matchers
@Test
public void fetchCustomers() throws Exception {
final User anyAdminUser = newUser().markAsAdmin().build();
context.checking(new Expectations() {{
oneOf(userSecurity).currentUser();
will(returnValue(anyAdminUser));
oneOf(customerBase).fetchCustomers();
will(returnValue(Lists.newArrayList(new Customer(1L, "::namespace_one::", ""), new Customer(2L, "::namespace_two::", ""))));
}});
Reply<?> reply = new CustomerService(customerBase, userSecurity, userBase).getCustomers();
assertThat(reply, isOk());
assertThat(reply, containsJson(aNewJsonArray().withElements(
aNewJson().add("id", 1L).add("namespace", "::namespace_one::"),
aNewJson().add("id", 2L).add("namespace", "::namespace_two::")
)));
}
public static Matcher<Reply<?>> containsJson(final JsonBuilder content) {
return new TypeSafeMatcher<Reply<?>>() {
@Override
protected boolean matchesSafely(Reply<?> item) {
Key<? extends Transport> key = property("transport", item);
// Default transport is Text which means that JSON transport
// wasn't specified and error should be returned.
if (Key.get(Text.class).equals(key)) {
return false;
}
String jsonContent = asJsonContent(item);
return jsonContent.equalsIgnoreCase(content.build());
}
@Override
public void describeTo(Description description) {
description.appendText(content.build());
}
@Override
protected void describeMismatchSafely(Reply<?> item, Description mismatchDescription) {
Key<? extends Transport> key = property("transport", item);
// Default transport is Text which means that JSON transport
// wasn't specified and error should be returned.
if (Key.get(Text.class).equals(key)) {
mismatchDescription.appendText("Text Transport was specified.");
return;
}
String jsonContent = asJsonContent(item);
mismatchDescription.appendText("was ");
mismatchDescription.appendText(jsonContent);
}
private String asJsonContent(Reply<?> reply) {
Object value = property("entity", reply);
return new Gson().toJson(value);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment