Value of Unit testing

There are probably uncountable amount of articles, posts and arguments on to why Unit Testing is so valuable. I just found a nice example that would’ve (or at least should’ve) been caught using Unit Tests. The following code was a bit adjusted to the need of this post, but has a mistake. See if you can spot it.

public class Discount
{
    public Discount(decimal percentage, DateTime startDate, DateTime endDate)
    {
        endDate.Add(new TimeSpan(23,59,59));

        Percentage = percentage;
        StartDate = startDate;
        EndDate = endDate;            
    }

    public decimal Percentage { get; private set; }
    public DateTime StartDate { get; private set; }
    public DateTime EndDate { get; private set; }
}

If you haven’t spotted it, I’d advise you to write a unit test to show that it’s failing. Here’s mine.

I’ve used FluentAssertions by the way, a library I love that helps me assert my code more easily.

[TestMethod]
public void Does_MapPropertiesCorrectly_When_CreatingNormalDiscount()
{
    // Act
    Discount discount = new Discount(5, new DateTime(2001, 9, 11), new DateTime(2011, 9, 11));

    // Assert
    discount.EndDate.Should().Be(new DateTime(2011, 9, 11, 23, 59, 59));
}

What is says is that it’s still 2011/9/11 00:00:00 instead of at the last second of that day. The problem here is that the endDate.Add method adheres to the framework guidelines. That is that you can’t edit an object you get passed by external source, only return new values. So the Add method returns a new DateTime object. We can make the test working with the following adjustment.

public class Discount
{
    public Discount(decimal percentage, DateTime startDate, DateTime endDate)
    {
        endDate = endDate.Add(new TimeSpan(23,59,59));

        Percentage = percentage;
        StartDate = startDate;
        EndDate = endDate;            
    }

    public decimal Percentage { get; private set; }
    public DateTime StartDate { get; private set; }
    public DateTime EndDate { get; private set; }
}

The only change I made was on line 5.

You may also like...

3 Responses

  1. Patrick Wellink says:

    Did you experiment with datetime.kind ?

    See : http://bloggingabout.net/blogs/wellink/archive/2011/09/02/something-you-really-should-know-about-dates-beeing-kind-to-datetime-kind.aspx

    What happens if kind is not equal for the dates…..

    Say startdate = 01-01-2000 kind = unspecified and
    enddate = 02-01-2001 UTC -11 kind = specified….

  2. MarkO says:

    What about:

    Discount discount = new Discount(5, new DateTime(2001, 9, 11), new DateTime(2011, 9, 11, 16,0,0));

  3. Dennis van der Stelt says:

    @MarkO : What about it??? I don’t get your point?

Click on a tab to select how you'd like to leave your comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.