Search code examples
c#.net-corexunitfluent-assertions

How to insert a message at the first line if there is a failure in an AssertionScope in FluentAssertions?


I'm looping through an array of results and comparing each object to the array of expected results resultItem.Should().BeEquivalentTo(expectedResultItem). Each item have a unique identifier and want to display it above.

Here is an example result and the first two rows are from a single call of BeEquivalentTo while the 3rd entry is from a different one:

Expected property resultItem.PropertyA to be "85.01", but "85.00" differs near "0" (index 4).
Expected property resultItem.PropertyB to be 85.01M, but found 85.00M.
Expected step to be MyProject.Models.ResultItem
{
    IdA = "620",
    IdB = "Total", 
    PropertyA = "12156.00", 
    PropertyB = 12156.0M, 
    PropertyC = 33
}, but found <null>.

Is it possible to insert more details above each result as some form of header? Something like this:

Error found on entry (IdA:12, IdB: "ABC")
Expected property resultItem.PropertyA to be "85.01", but "85.00" differs near "0" (index 4).
Expected property resultItem.PropertyB to be 85.01M, but found 85.00M.
Error found on entry (IdA:620, IdB: "Total")
Expected step to be MyProject.Models.ResultItem
{
    IdA = "620",
    IdB = "Total", 
    PropertyA = "12156.00", 
    PropertyB = 12156.0M, 
    PropertyC = 33
}, but found <null>.

Solution

  • While this isn't ideal readability, you can abuse FA's because argument to have it output some context:

    [TestMethod]
    public void AssertionContext()
    {
      using (new AssertionScope())
      {
        Foo resultItem = new Foo { PropA = "123.0", PropB = 123.0m, Id = 777 };
        resultItem.Should().BeEquivalentTo(new { PropA = "123.1", PropB = 123.1m }, "ID {0} should match", resultItem.Id);
    
        Foo step = null;
        step.Should().BeEquivalentTo(new Foo { PropA = "123.0", PropB = 123.0m }, "ID {0} should match", 987654);
      }
    }
    
    Expected property resultItem.PropA to be "123.1" because ID 777 should match, but "123.0" differs near "0" (index 4).
    Expected property resultItem.PropB to be 123.1M because ID 777 should match, but found 123.0M.
    Expected step to be Foo
    {
        Id = 0, 
        PropA = "123.0", 
        PropB = 123.0M
    } because ID 987654 should match, but found <null>.