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?
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.
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.
We specify the time unit in test suites and test cases is in milliseconds.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With