How can today's date vary for unit testing purposes?

I am using VS2008 for the .NET 2.0 Framework, and just in case, I cannot change this :)

I have a class DateCalculator. His method GetNextExpirationDatetries to determine the next ending by using internally DateTime.Todayas the base date.

Since I wrote unit tests, I realized that I wanted to test GetNextExpirationDatefor different “today's” dates.

What is the best way to do this? Here are a few alternatives that I have reviewed:

  • Derive a property / overloaded method with an argument baselineDateand use it only from unit test. In the actual client code, ignore the property / overloaded method in favor of the method, which by default baselineDateis DateTime.Today. I do not want to do this because it makes the public interface of the DateCalculator class inconvenient.
  • Create a protected field under the name baselineDatethat is internally set to DateTime.Today. When testing, output DateCalculatorForTestingfrom DateCalculatorand install baslineDatethrough the constructor. It ensures the cleanliness of the public interface, but is still small - it baselineDateis protected and requires a derived class, both for testing and testing.
  • Use extension methods. I tried this after adding ExtensionAttribute, and then realized that this would not work, because extension methods cannot access private / protected variables. Initially, I thought it was really a very elegant solution. :(

I would be interested to know what others think.

+5
source share
4 answers

I usually collect OS calls inside an abstraction / interface so that I can easily test them. Like Andrew, as mentioned above.

However, considering only the need mentioned in the question; I believe that “Subclass and Overriding” is the easiest and least invasive way to do this - Option 2 mentioned by OP.

public class DateCalculator
{
  public DateTime GetNextExpirationDate() {  // call to GetBaseLineDate() to determine result }
  virtual protected GetBaseLineDate() {  return DateTime.Today; }
}

// in your test assembly
public class DateCalcWithSettableBaseLine : DateCalculator
{
  public DateTime BaseLine { get; set;}
  override protected GetBaseLineDate()
  {    return this.BaseLine;  }
}
+1
source

, . , DateTime.Today, , .

, - , , .

, , : : DateTime.Now

+4

- , DateTime, :

public DateTime GetNextExpirationDate()
{
  return GetNextExpirationDate(DateTime.Today);
}

internal DateTime GetNextExpirationDate(DateTime after)
{
  // implementation goes here
}

InternalsVisibleToAttribute, , DateTime .

+1
source

You can change the operating time of the operating system on the computer performing the test. It's easy and transparent, but watch out for issues with file timestamps.

0
source

All Articles