开发者

using string.Format and UnitTest dates

开发者 https://www.devze.com 2023-04-12 03:21 出处:网络
Dates and formatting have always been a bit of a nightmare for me. Lately I am doing lots of writing to file where dates must be convertted to strings in various formats(depending on client).

Dates and formatting have always been a bit of a nightmare for me. Lately I am doing lots of writing to file where dates must be convertted to strings in various formats(depending on client).

I would like to create a unittest that can consolidate the lot just put a couple of example.

The below test fails as "March 09" and "09 March" do not match.How do I make this test culture aware. Better test anyone?

        [TestCase("March 09", "{0:m}")]                        
        [Tes开发者_Go百科tCase("March, 2008", "{0:y}")]  
             [TestCase("3/9/2008 4:05 PM", "{0:g}")                       
        public void When_stringFormat_a_date_should_match(string expected,string format)
        {
            DateTime dt = new DateTime(2008, 03, 09, 16, 05, 07);

            string actual = String.Format(format, dt);

           assert ??                
        }


You're calling String.ToString()! It doesn't make sense to specify the CultureInfo (or even use this functio), since this always returns the original string independently of the specified culture.

IMO you have to specify the CultureInfo when converting the date, i.e.

string actual = String.Format(CultureInfo.InvariantCulture, format, dt);
Assert.AreEqual(expected, actual);


Assert.AreEqual(expected, actual);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号