Created
July 12, 2012 13:56
-
-
Save miguelbaldi/3098239 to your computer and use it in GitHub Desktop.
JUnit rule for expected exception
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
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