FluentAssertions and code formatting

Recently I was playing with FluentAssertions library. I was really amazed by the beautiful error messages generated by FluentAssertions. For example, for this failing test:

[Fact]
public void add_returns_sum_of_its_arguments() {
    // Arrange
    var service = new ServiceA();
    
    // Assert
    service.Add(1, 2).Should().Be(3);
}

FluentAssertions generates a message:

Outcome: Failed
Error Message:
Expected service.Add(1, 2) to be 3, but found 42.

Unfortunatelly my joy did not last long. When I added an explanation to an assertion and broke the line because it got too long:

[Fact]
public void add_returns_sum_of_its_arguments() {
    // Arrange
    var service = new ServiceA();

    // Assert
    service.Add(1, 2)
        .Should().Be(3, because: "three is sum of one and two");
}

FluentAssertions reproted just:

Outcome: Failed
Error Message:
Expected value to be 3 because three is sum of one and two,
    but found 42.

It turns out, in order to have these fancy error messages, we must place .Should() on the same line as the tested expression:

[Fact]
public void add_returns_sum_of_arguments() {
    // Arrange
    var service = new ServiceA();

    // Assert
    service.Add(1, 2)/*abra cadabra*/.Should()
        .Be(3, because: "three is sum of one and two");
}

The above test generates a message:

Outcome: Failed
Error Message:
Expected service.Add(1, 2)/*abra cadabra*/ to be 3 because three
   is sum of one and two, but found 42.

Notice that comment was also include in the message.

This behavior of FluentAssertions really suprised me. Why the way we format our code have influence over the readability of error messages?

Anyway this is how FluentAssertions works, moreover this behaviour is described (with short explanation how it works) on the first page of the official documentation. If only I have spend ten minutes reading the friendly docs instead of skimming it…

From now on I will follow “Read The Friendly Manual” (RTFM) advice!!!