Skip to content

Instantly share code, notes, and snippets.

@hjerpbakk
Last active December 23, 2015 20:29
Show Gist options
  • Save hjerpbakk/6690110 to your computer and use it in GitHub Desktop.
Save hjerpbakk/6690110 to your computer and use it in GitHub Desktop.
A well designed unit test example where the current day is hidden behind an abstraction. From: http://hjerpbakk.com/blog/2013/9/24/the-little-test-that-could-not.html
[TestFixture]
public class GoodUnitTestExample {
[Test]
public void AgeMustReturnCorrectAge() {
IClock clock = new StubClock(new DateTime(2013, 9, 2));
var aPerson = new PersonGood(clock) { TimeOfBirth = new DateTime(1983, 9, 8) };
Assert.AreEqual(29, aPerson.Age);
}
}
public class PersonGood {
private readonly IClock clock;
public PersonGood(IClock clock = null) {
this.clock = clock ?? new Clock();
}
public DateTime TimeOfBirth { get; set; }
public int Age {
get {
var today = clock.Today;
int age = today.Year - TimeOfBirth.Year;
if (TimeOfBirth > today.AddYears(-age)) --age;
return age;
}
}
}
public interface IClock {
DateTime Today { get; }
}
public class Clock : IClock {
public DateTime Today { get { return DateTime.Today; } }
}
public class StubClock : IClock {
private readonly DateTime now;
public StubClock(DateTime now) {
this.now = now;
}
public DateTime Today {
get {
return now.Date;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment