Unit Tests with cross-cutting concerns

Did you ever have trouble with writing tests where your class-under-test (cut) was dealing with cross-cutting concerns such as time management?

The following text is a 90% copy of the 7.5 chapter from the book „The Art of Unit Testing„:

The problem with cross-cutting concerns like DateTime is that when they exist in your code, they´re used in so many places that architecting them as injectable pieces of Lego can end up making your code very testable but also very hard to read and follow.

Let´s say that your application needs the current time for scheduling or for logging, and you´d also like to test that your application is using the current time in its logs.

You might have this type of code in your system:

If you were to make it more testable by making an ITimeProvider interface, you´d then have to use this interface everwhere DateTime is used. This is very time consuming, when in fact you can have more straightforward approaches.

It is much easier when you create a custom class, named SystemTime, and make sure all your production code uses that class instead of the standard built-in DateTime.

Now you can alter the current time throughout the system. This gives you a perfect way to test that the current time is used in your production code through a simple test like the one following:

You don´t have to inject a million interfaces into your production code. The price you pay is a simple [TearDown] method in your test class that makes sure any test doesn´t change the time for other tests.

Tutorial for Test Driven Development

Have you ever tried TDD and failed (for several reasons)? Do you wanna give it a try again with a valueable tutorial by your side. Than try out the free ebook of Grzesiek Galezowski:


This ebook does not only mention basics of TDD but also very important principles of Object-oriented programming (SRP, ISP, Object Composability, How to start writing valueable tests before even start writing productive code, etc.)

Give it a try!