Dan North, in a recent article about DRY tests, says:
[Tests] are the documentation narrative that will guide future programmers (including yourself when you come back to change this code in three months time and you’ve forgotten what it does). In this case, clarity of intent is found in the quality of the narrative, not necessarily in minimising duplication.
I had a painful experience with DRY tests the other day. The code looked something like this, but on a larger, more hideous scale:
[Fact] public void SomeServiceWorks() { using (var service = new Service()) { RunTest(service); } } [Fact] public void AnotherTest() { using (var service = Service.MyService) { CheckProps(service); } } private static void CheckProps(Service service) { Assert.NotNull(service.OtherThing); RunTest(service); } private static void RunTest(Service service) { Assert.NotNull(service.Something); }
So while the code is not clear, it is easy to see what the author was trying to do - keep his tests DRY. With a lot of tests this makes it very difficult to understand exactly what is going on.
Resharper has a nifty new refactoring that lets us do an Inline Method to clarify these tests. Just insert at the method name and use the Ctrl-Alt-N shortcut:
![]()
I think the resulting code is much easier to read.
[Fact] public void SomeServiceWorks() { using (var service = new Service()) { Assert.NotNull(service.Something); } } [Fact] public void AnotherTest() { using (var service = Service.MyService) { Assert.NotNull(service.OtherThing); Assert.NotNull(service.Something); } }
Leave a reply