Skip to content

Instantly share code, notes, and snippets.

@miguelbaldi
Created July 12, 2012 13:56
Show Gist options
  • Save miguelbaldi/3098239 to your computer and use it in GitHub Desktop.
Save miguelbaldi/3098239 to your computer and use it in GitHub Desktop.
JUnit rule for expected exception
public class TripServiceTest {
private static final User UNUSED_USER = null;
private static final User NON_LOGGED_USER = null;
private User loggedUser = new User();
private User targetUser = new User();
private TripService tripService;
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void initialise() {
tripService = createTripService();
}
@Test public void
shouldThrowExceptionWhenUserIsNotLoggedIn() throws Exception {
loggedUser = NON_LOGGED_USER;
exception.expect(UserNotLoggedInException.class);
tripService.getTripsByUser(UNUSED_USER);
}
@Test public void
shouldNotReturnTripsWhenLoggedUserIsNotAFriend() throws Exception {
List<Trip> trips = tripService.getTripsByUser(targetUser);
assertThat(trips.size(), is(equalTo(0)));
}
@Test public void
shouldReturnTripsWhenLoggedUserIsAFriend() throws Exception {
User john = anUser().friendsWith(loggedUser)
.withTrips(new Trip(), new Trip())
.build();
List<Trip> trips = tripService.getTripsByUser(john);
assertThat(trips, is(equalTo(john.trips())));
}
private TripService createTripService() {
return new TripService() {
@Override protected User loggedUser() {
return loggedUser;
}
@Override protected List<Trip> findTripsByUser(User user) {
return user.trips();
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment