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.

  • 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
    Dec 2 '13 at 13:04

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) {

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

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

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

  • 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
    Dec 22 '13 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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