From 10a947c0de0532f0825201001130d7fcb6b2c68c Mon Sep 17 00:00:00 2001 From: Gustavo Martin Morcuende Date: Thu, 24 Nov 2016 01:50:37 +0100 Subject: [PATCH] Improvement with fluent interface for our test We now have the legacy code under test. So now and not before we can refactor the legacy code. --- .../tripservicekata/trip/TripServiceShould.java | 57 ++++++++++++++++++---- 1 file changed, 48 insertions(+), 9 deletions(-) diff --git a/TDD/src/test/java/org/craftedsw/tripservicekata/trip/TripServiceShould.java b/TDD/src/test/java/org/craftedsw/tripservicekata/trip/TripServiceShould.java index 3b87700..e2a58ba 100644 --- a/TDD/src/test/java/org/craftedsw/tripservicekata/trip/TripServiceShould.java +++ b/TDD/src/test/java/org/craftedsw/tripservicekata/trip/TripServiceShould.java @@ -36,9 +36,10 @@ public class TripServiceShould { @Test public void not_return_any_trips_when_users_are_not_friends() { - User friend = new User(); - friend.addFriend(ANOTHER_USER); - friend.addTrip(TO_BRAZIL); + User friend = UserBuilder.aUser() + .friendsWith(ANOTHER_USER) + .withTrips(TO_BRAZIL) + .build(); List friendTrips = tripService.getTripsByUser(friend); // You must always begin writing the assert. @@ -48,12 +49,11 @@ public class TripServiceShould { } @Test public void - return_friend_trips_when_users_are_friends() { - User friend = new User(); - friend.addFriend(loggedInUser); - friend.addFriend(ANOTHER_USER); - friend.addTrip(TO_BRAZIL); - friend.addTrip(TO_BERLIN); + return_friend_trips_when_users_are_friends() { + User friend = UserBuilder.aUser() + .friendsWith(ANOTHER_USER, loggedInUser) + .withTrips(TO_BRAZIL, TO_BERLIN) + .build(); List friendTrips = tripService.getTripsByUser(friend); // You must always begin writing the assert. @@ -62,6 +62,45 @@ public class TripServiceShould { assertThat(friendTrips.size(), is(2)); } + + public static class UserBuilder { + private User[] friends = new User[]{}; + private Trip[] trips = new Trip[]{}; + + public static UserBuilder aUser() { + return new UserBuilder(); + } + + public UserBuilder withTrips(Trip...trips) { + this.trips = trips; + return this; + } + + public UserBuilder friendsWith(User...friends) { + this.friends = friends; + return this; + } + + public User build() { + User user = new User(); + addTripsTo(user); + addFriendsTo(user); + return user; + } + + private void addFriendsTo(User user) { + for (User friend : friends) { + user.addFriend(friend); + } + } + + private void addTripsTo(User user) { + for (Trip trip : trips) { + user.addTrip(trip); + } + } + } + private class TesteableTripService extends TripService { @Override -- 2.1.4