How NOT to test drive time dependant functionalities

Recommended reading before you read this article: Fest assertions, Testing time dependant functionalities .

Do NOT do this!

I would like to present an example of an attempt to test time dependant functionality in a not very nice in my opinion way. Please see testing time dependant functionalities for the recommended way.

Below I present two very similar ways of trying to test drive time dependant functionalities. Please remember that the recommended way it to introduce a clock class.

Approach by extending Fest (DO NOT DO THIS)

Approach by extending Hamcrest (DO NOT DO THIS)

Why avoid this approach?

Think about it. Is “is within one second” actually what you are looking for? Probably not. You are looking for “is now”.
The other argument is that is reduces readability.

Testing time dependant functionalities

Recommended reading before you read this article: Mockito basics, Fest assertions.

How do we test time dependent operations?

Let us assume we have a report and it may me marked as complete. When it is marked as complete the “completed on” date should be set. The easiest approach would be to do a “new Date()” and assign it to “completed on” attribute.

But how do we test it? We have to take an other approach.
The solution is to introduce a Clock object that can be asked for the current time and which we will be able to mock in tests:

Recommended further reading: How NOT to test drive time dependant functionalities