DEV Community

Matheus Rodrigues
Matheus Rodrigues

Posted on • Originally published at matheus.ro on

1 2

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

👋 One thing before you go

Tired of spending so much on your side projects? 😒

We have created a membership program that helps cap your costs so you can build and experiment for less. And we currently have early-bird pricing which makes it an even better value! 🐥

Just one of many great perks of being part of the network ❤️

Top comments (0)

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay