1

I have a method Fetch, GetExchangeRate and method FetchOnDemand. FetchOnDemand checkds if Fetch is not called during one day it calls it.

GetExchangeRate calls FetchOnDemand first then does its particular job.

How can I test a FetchOnDemand.

1
  • Could you elaborate on how FetchOnDemand checks if Check has been called? Best scenario would be a code sniplet that shows how your components are structured... What inputs / outputs do you have?
    – Martin
    Commented Dec 2, 2013 at 13:04

2 Answers 2

5

I assume you are asking how to test code that is time-dependent.

One strategy is to refactor the code under test so that you control the definition of the current time. For example, in Java, instead of calling System.currentTimeMillis(), you might call a method on a "time provider" interface. The default to implementation of that interface would call System.currentTimeMillis(). For test purposes, you would use a test implementation that would return a time that you would control.

Another strategy is to provide a way to override your reference time. Suppose your code looks like this:

Fetch() {
    fetch something;
    lastFetchTime = current time;
}

FetchOnDemand() {
   if (lastFetchTime is at least a day ago) {
      Fetch();
   }
}

If you add a SetLastFetchTime() method, your test can control lastFetchTime.

5
  • and what about .NET?
    – TIKSN
    Commented Dec 3, 2013 at 19:30
  • Perhaps you could lookup the .NET API for getting the current system time.
    – user246
    Commented Dec 3, 2013 at 20:39
  • Creating an interface for getting a time in module does not sounds good for me. Can you suggest anything else?
    – TIKSN
    Commented Dec 4, 2013 at 10:05
  • Done. This isn't hard, but it still requires adding test hooks to the code under test.
    – user246
    Commented Dec 5, 2013 at 0:08
  • I am building framework, I can't add methods like that.
    – TIKSN
    Commented Dec 5, 2013 at 18:38
3

This is a great article on the subject that I've found very comprehensive and helpful. It's great for starting the conversation with your development team to make these sorts of things more test-friendly.

Eradicating Non-Determinism in Tests

1
  • Very good article but unfortunately it did not helped me with my time issue because in .NET you cannot change a system time. Even more my tests should be running on Visual Studio Online, which won't let me to change its system time.
    – TIKSN
    Commented Dec 22, 2013 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.