Search code examples
c#fluent-assertions

How to correctly combine Using and WhenTypeIs<DateTime> in Fluent Assertions


I have a dictionary of objects like so: Attributes = new Dictionary<string, object>();

Within the dictionary is a DateTime, I am trying test if that DateTime falls on a particular day, like so:

Attributes[key].ShouldBeEquivalentTo(DateTime.Now, options => options
    .Using<DateTime>(ctx =>
    {
        //throw new InvalidOperationException();
        ctx.Subject.Should().BeSameDateAs(ctx.Expectation);
    }).WhenTypeIs<DateTime>());

However this results in the failed assertion Expected subject to be <2016-06-30 11:38:05.447>, but found <2016-06-30 10:38:05>. The dates are on the same date so I believe should pass, but the assertion has failed.

This leads me to conclude that the line ctx.Subject.Should().BeSameDateAs(ctx.Expectation) is not being applied. I tried adding an exception, and debugging but it appears the code in the action is never reached.

Should I expect this work? I am doing this correctly?


Solution

  • Code in action is never reached because ShouldBeEquivalentTo is supposed to compare object graph (properties of actual and expected). Using...WhenTypeIs<DateTime> will be applied to properties of type DateTime.

    In your case object is DateTime itself, so you can assert that it is indeed DateTime and chain other required assertions:

    Attributes[key].Should().BeOfType<DateTime>().Which.Should().BeSameDateAs(DateTime.Now);