Unit test for method block that will occur daily



  • 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.



  • 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.


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2