rexcfnghk
rexcfnghk

Reputation: 15442

Unit testing DateTime strings

I have a class that converts a string into a DateTime and perform some business logic in it:

public class Foo
{
    public Foo(string value)
    {
        Value = DateTime.Parse(value);
    }

    public DateTime Value { get; }

    // Some additional methods
}

I would like to unit test Foo so that it only accepts valid datetime strings, so I wrote a unit test:

public class FooTests
{
    [Fact]
    public void Foo_ValidDateTimeString_Returns()
    {
        const string testInput = "2015-01-01";

        var result = new Foo(testInput);

        var expected = new DateTime(2015, 1, 1);
        Assert.Equal(expected, result.Value);
    }
}

This test passes in various cultures such as en-US.

My concern is, this unit test will fail when another colleague who is under a different CultureInfo which does not accept yyyy-MM-dd as a valid DateTime format.

I do not want to enforce the test to be run under a specific CultureInfo in order to make the test pass. Is there another way?

Upvotes: 2

Views: 3589

Answers (2)

Soner Gönül
Soner Gönül

Reputation: 98750

I do not want to enforce the test to be run under a specific CultureInfo in order to make the test pass. Is there another way?

No.

Using the CurrentCulture on the system is usually a bad idea, because the string that you provided can mean different things for different culture settings.

For example; 2015-01-02 can mean 1st February or 2nd January for different cultures with using DateTime.Parse(string) overload.

DateTime.ParseExact with a specific culture is a much more detailed, controlled and exact approach.

This stated in documentation as well;

Because the Parse(String) method tries to parse the string representation of a date and time using the formatting rules of the current culture, trying to parse a particular string across different cultures can either fail or return different results. If a specific date and time format will be parsed across different locales, use the DateTime.Parse(String, IFormatProvider) method or one of the overloads of the ParseExact method and provide a format specifier.

Upvotes: 1

tchrikch
tchrikch

Reputation: 2468

You can always use CultureInfo.InvariantCulture as argument to Parse() method

    Value = DateTime.Parse(value,CultureInfo.InvariantCulture);

so that you don't have to care about culture inside unit-tests. Another way, if you want to keep data as-is the other way is to go for exact parsing

   Value = DateTime.ParseExact(value,"yyyy-MM-dd",CultureInfo.InvariantCulture);

Upvotes: 3

Related Questions