Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write testcase for testing things like "30 days expire"?

Tags:

unit-testing

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?

like image 683
frankshaka Avatar asked Apr 03 '12 04:04

frankshaka


2 Answers

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.

like image 179
TGH Avatar answered Sep 27 '22 19:09

TGH


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

like image 35
Ivan Gerken Avatar answered Sep 27 '22 21:09

Ivan Gerken