Skip to content

Instantly share code, notes, and snippets.

@olafleur
Last active November 2, 2015 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olafleur/f64944f71079c7167576 to your computer and use it in GitHub Desktop.
Save olafleur/f64944f71079c7167576 to your computer and use it in GitHub Desktop.
class Endpoint {
private final UserInformationService userInformationService;
private final ResponseFactory responseFactory;
Endpoint(UserInformationService userInformationService, ResponseFactory responseFactory) {
this.userInformationService = userInformationService;
this.responseFactory = responseFactory;
}
public Response getUsername(int id) {
try {
String username = userInformationService.getUsername(id);
return responseFactory.createOk(username);
}
catch (NotFoundException ex) {
return responseFactory.createNotFound();
}
}
}
// This test is written using mockito, and the creation of mock object was omitted to keep it brief.
private final String A_USERNAME = "Bobby";
private final int USER_ID = 1337;
@Test
public void getUsername_delegatesToUserInformationService() {
endpoint.getUsername(USER_ID);
verify(userInformationService).getUsername(USER_ID);
}
@Test
public void getUsername_returnsOkWhenUserIsFound() {
Response OK_RESPONSE = new OkResponse();
given(responseFactory.createOk(A_USERNAME)).willReturn(OK_RESPONSE);
given(userInformationService.getUsername(USER_ID)).willReturn(A_USERNAME);
Response result = endpoint.getUsername(USER_ID);
assertThat(result).isSameAs(OK_RESPONSE);
}
@Test
public void getUser_returnsNotFoundWhenUserIsNotFound() {
Response NOT_FOUND_RESPONSE = new NotFoundResponse();
given(responseFactory.createNotFound()).willReturn(NOT_FOUND_RESPONSE);
given(userInformationService.getUsername(USER_ID)).willThrow(NotFoundException.class);
Response result = endpoint.getUsername(USER_ID);
assertThat(result).isSameAs(NOT_FOUND_RESPONSE);
}
@Pacane
Copy link

Pacane commented Oct 9, 2015

@olafleur can you fix this snippet and put the fields of Endpoint private final

Also, I wonder if the test code would be cleaner if we'd group the given parts together. Making a clear given/when/then separation

-- thanks

@olafleur
Copy link
Author

olafleur commented Nov 2, 2015

Done.

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