Last active
November 2, 2015 20:27
-
-
Save olafleur/f64944f71079c7167576 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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