From: Gustavo Martin Morcuende Date: Sun, 4 Dec 2016 18:32:51 +0000 (+0100) Subject: Clock test is green. X-Git-Url: https://git.gumartinm.name/?a=commitdiff_plain;h=2e164170069ed34a086056ba77d737f4719e592d;p=JavaForFun Clock test is green. Inline as much code as possible (getting ride of variables) We isolate and control the randomness in our code. No using spies, instead, we use private classes in our tests. --- diff --git a/TDD/sandromancuso/bank/src/main/java/org/craftedsw/feature/Clock.java b/TDD/sandromancuso/bank/src/main/java/org/craftedsw/feature/Clock.java index 9b964b3..f5c8798 100644 --- a/TDD/sandromancuso/bank/src/main/java/org/craftedsw/feature/Clock.java +++ b/TDD/sandromancuso/bank/src/main/java/org/craftedsw/feature/Clock.java @@ -5,10 +5,15 @@ import java.time.format.DateTimeFormatter; public class Clock { + private static final DateTimeFormatter DD_MM_YYYY = DateTimeFormatter.ofPattern("dd/MM/yyyy"); + public String todayAsString() { - // We need to control this random stuff for our tests. :( - LocalDate today = LocalDate.now(); - return today.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")); + return today().format(DD_MM_YYYY); + } + + // We isolated the randomness in here. + protected LocalDate today() { + return LocalDate.now(); } } diff --git a/TDD/sandromancuso/bank/src/test/java/org/craftedsw/feature/ClockShould.java b/TDD/sandromancuso/bank/src/test/java/org/craftedsw/feature/ClockShould.java index 24f33d5..fd54ef7 100644 --- a/TDD/sandromancuso/bank/src/test/java/org/craftedsw/feature/ClockShould.java +++ b/TDD/sandromancuso/bank/src/test/java/org/craftedsw/feature/ClockShould.java @@ -3,17 +3,28 @@ package org.craftedsw.feature; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; +import java.time.LocalDate; + import org.junit.Test; public class ClockShould { @Test public void return_todays_date_in_dd_MM_yyyy_format() { - Clock clock = new Clock(); + Clock clock = new TestableClock(); String date = clock.todayAsString(); assertThat(date, is("04/12/2016")); } + private class TestableClock extends Clock { + + @Override + protected LocalDate today() { + // We will control the random part of our code + // (no need of using spy) + return LocalDate.of(2016, 12, 4); + } + } }