RShome
RShome

Reputation: 537

How to assert the date format of a string using Shouldly and c#

I would like to check that the string from a textbox is of format "dd-MMM-yyyy" e.g. 14-Mar-2023 I have written the following code but I get an error

string date = Page.HeaderDate().Text
date.Should().Be(string.Format("dd-MMM-yyyy")

Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException: 'Expected date to be "dd-mmm-yyyy", but "14-Mar-2023" differs near "14-" (index 0).'

Any ideas,thoughts much appreciated.

Thanks

Upvotes: 0

Views: 261

Answers (1)

RShome
RShome

Reputation: 537

This worked for me.

    string date = Page.HeaderDate().Text;
    DateTime dateTime;
    string[] formats = new[] { "dd-MMM-yyyy" };

    // Verify the extracted completed date is in "dd-MMM-yyyy" format.
    DateTime.TryParseExact(date, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime).ShouldBeTrue();
   
        

Upvotes: 0

Related Questions