Fluent Assertion - Compare DateTime to String

cionsi

New member
Joined
May 2, 2022
Messages
1
Programming Experience
1-3
Hi guys, I was trying to make it easier to compare two objects in tests.
Specifically I have to check two props that contain a date, but in the first case the date is of type DateTime, in the second case it is of type String.
This is the code that I was able to produce after several searches.

The difference between date and string is also and especially for the format of which I might want different formats.

C#:
var expected = new UserDao()
{
    Name = "Name",
    Age = 10,
    BirthDate = new DateTime(2022,10,5, 1, 0, 0),
    HireDate = new DateTime(2022, 2, 15, 1, 0, 0)
    };
var result = new UserDto()
{
    Name = "Name",
    Age = 10,
    BirthDate = "05-10-2022",
    HireDate = "15-02-2022"
    };

result.Should().BeEquivalentTo(expected, opt =>
                               opt.Using<object>(ctx => ctx.Subject.Should().Be(CustomDateToString((DateTime)ctx.Expectation)))
                               .WhenTypeIs<DateTime>());

private string CustomDateToString(DateTime date)
        {
            return date.ToString("dd-MM-yyyy");
        }

I couldn't find anything better with my research. Do you have any advice?
 
You could implement IEquatable<T> on your DAO and DTO classes.
 
Or you could implement a pair of extension methods called IsEqual() that does string to DateTime comparisons.
 
Back
Top Bottom