I want to write some test cases for my web app, but stuck at some cases such as "This token should be expired in 30 days". Nobody likes to wait for 30 days before the tests finish.
There are also other cases regarding some scheduled events to happen, like "Send this email 2 weeks after the user sign up", "Generate a bill 2 days before next billing date", etc.
What suggestion do you have on writing such test cases? Or, is there another way of making sure that these functions work as precisely as designed?
My approach when writing these tests is to define the expiration in milliseconds. That way you can easily write tests because your test environments can define an expiration of 1 ms. The production environment will obviously define the appropriate duration. Typically these can be set as config values or db values.
I suppose you have some code like
if(token.ExpirationDateTime > DateTime.Now)
{
// do some job to expire
}
Usually I provide the classes with such logic with an injected field of type Func<DateTime>
. For example
public class ExpirationManager
{
private Func<DateTime> _nowProvider;
public ExpirationManager(Func<DateTime> nowProvider)
{
_nowProvider = nowProvider;
}
}
Then the expiration code looks like
if(token.ExpirationDateTime > _nowProvider())
{
// do some job to expire
}
This way you can substitute the real current system time with whatever DataTime you want when doing tests (e.g. unit tests).
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