DEV Community

Matheus Rodrigues
Matheus Rodrigues

Posted on • Originally published at matheus.ro on

Unit Test And Time Dependency

When you start to write unit tests, inevitably you’ll encounter a hard time when a functionality depends on time. Depend on DateTime.Now doesn’t work well for unit testing, your tests will pass on certain time of day and fail in others.

To resolve this problem we need to isolate the time dependency of system, to be able to make our unit test reliable.

Example

So, we have a shop that gives some discount based on the hour of the day, and we have a method that return how much the discount will be:

public class Shop
{
    //Constructor
    //public Shop(.....

    //Other Implementations
    //.....

    public int GetCurrentDiscount()
    {
        switch (DateTime.Now.Hour)
        {
            case 9:
                return 30;
            case 12:
                return 20;
            case 18:
                return 40;
            default:
                return 0;
        }
    }
}

Continue Reading...

Top comments (0)