1

Is there a common knowledge pattern or idiom to solve the problem that code that uses new Date() is extremely hard to unit-test?

I know a possible solution (e.g. http://refactoringaspnet.blogspot.com/2010/02/unit-testing-code-which-is-dependent-on.html), but the question is whether there is a common pattern and language for this problem.

bertolami
  • 2,896
  • 2
  • 24
  • 41
  • See http://stackoverflow.com/questions/4454106/how-can-i-mock-jodatime-actual-date – skaffman Feb 04 '11 at 08:47
  • Thanks. But this is just another solution. I am looking for a pattern and thus common language, but it seems that everbody is doing it in its own way. Even tough the solution is simple, a pattern/idiom would help in communication. – bertolami Feb 04 '11 at 09:09

4 Answers4

2

What I sometimes do is build an Interface that is responsible for returning the date. for example:

public interface ISystemClock
{
    DateTime GetCurrentDate();
}

this could then be mocked out if required for unit tests.

saret
  • 2,217
  • 13
  • 12
  • I try this, but I have some issue with it. Here is my post, can u take a look? http://stackoverflow.com/questions/6049777/mockito-how-to-mock-an-interface-of-jodatime – Thang Pham May 18 '11 at 19:22
1

The idea is to simply move anything that is difficult to test (i.e. difficult to control for the purposes of unit testing) behind an interface. Follow that up with a Fake or a Mock which gives you the required control.

The blogpost that you linked in the question is right for the most part.. However I personally wouldn't do the last bit of creating a TestableClock which instantiates the dependency. I'd prefer to pass it in as a ctor argument or a method parameter.

Gishu
  • 134,492
  • 47
  • 225
  • 308
0

If I don't understood wrongly your needs, you're looking for "mocking":

That's providing a fake implementation for some underlying code that's not part of the test, but it must work properly in order to successfully test some logic.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
  • In Java it is not so trivial, and probably not so good practice to mock Calendar.getInstance() – bertolami Feb 04 '11 at 08:46
  • Well in .NET we've a good project called "Moles" which create a mocked version of any class in any assembly (I believe that "assembly" for Java is "jar"), so it becomes trivial. For example, if you've DateTime.Now, Moles creates a MDateTime.Now "Mocked DateTime", and you can change what "NoW" does by setting in it a lambda expression. Maybe Java has something like Moles? – Matías Fidemraizer Feb 04 '11 at 08:50
0

That is it. You'll have to mock/fake the reading of the time. This can extend beyond just the system time. You could have a general "environment" interface that allows you to gain control over other non-deterministic factors for your testing.

Ates Goral
  • 137,716
  • 26
  • 137
  • 190