Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnitTest a method that is time-dependent

How would you test a method that is time-dependent?

A simple example could be:

public static int GetAge(DateTime birthdate)
{
    // ...
}

[TestMethod]
public void GetAgeTest()
{
    // This is only ok for year 2013 !
    Assert.AreEqual(GetAge(new DateTime(2000, 1, 1)), 13);
}

The problem is that it will work only for the current year (2013 in this case). As soon as a new year begins, I have to rewrite all time-dependent tests...

What is the best approach to Unit Test such a method?

like image 952
Bidou Avatar asked Jul 03 '13 13:07

Bidou


People also ask

Which is a time-dependent test?

Time-dependent behavior with gel formation or curing This oscillatory test is performed under constant dynamic-mechanical conditions. Accordingly, both parameters – shear-strain (or shear-stress) amplitude and (angular) frequency – are kept constant in this test. In most cases, controlled-strain tests are preferred.

What are dependencies in unit testing?

So, what is a unit testing dependency? It's a dependency that you must set up in the test before you can exercise the system under test. Dependencies can be explicit, like in the example above, but they also can be implicit.

Which is the time unit that is used to specify in test cases?

We specify the time unit in test suites and test cases is in milliseconds.


2 Answers

You could override the mechanism by which your GetAge method finds today's date.

If you wrap DateTime in another class you can then replace the actual calls with fake calls that return known values while unit testing.

You can use dependency injection to switch between the real implementation for production and the fake implementation for testing.

like image 193
ChrisF Avatar answered Sep 21 '22 22:09

ChrisF


Also, don't forget the "Expected" argument is the first one in AreEquals.

[TestMethod]
public void GetAgeTest()
{
    int age = 13;
    Assert.AreEqual(age, GetAge(DateTime.Now.AddYears(age * -1));
}

Would also be better to split the test in Arrange - Act - Assert groups like this :

[TestMethod]
public void GetAgeTest()
{
    // Arrange
    int age = 13;

    // Act
    int result = GetAge(DateTime.Now.AddYears(age * -1);

    // Assert
    Assert.AreEqual(age, result);
}
like image 30
Pierre-Luc Pineault Avatar answered Sep 21 '22 22:09

Pierre-Luc Pineault