I am using FluentAssertions v5.9.0 and I am running into the following issue when using VS2017 + .Net Framework v4.7.1.
When the 'Optimize code' option is enabled in the Project properties under 'Build', it seems to affect FluentAssertions in some way, as shown in the simple example below.
Example code:
var a = false;
var b = false;
var c = false;
using (new AssertionScope())
{
a.Should().BeTrue();
b.Should().BeTrue();
c.Should().BeTrue();
}
Running the above code snippet with 'Optimize code' set to off on the project build properties, it yields the correct result, namely:
Expected a to be true, but found False.
Expected b to be true, but found False.
Expected c to be true, but found False.
When the 'Optimize code' option is enabled and the project is rebuild, the same code snippet yields the following test result (var a is skipped and var c is done twice)
Expected b to be true, but found False.
Expected c to be true, but found False.
Expected c to be true, but found False.
Versions
Visual Studio 2017
.Net runtime version = .Net Framework v4.7.1
FluentAssertions version = v5.9.0
The project output type is class library.
When you enable optimizations for your unit test code, FA will be unable to reliably extract the name of the variable from the stack trace. However, normally it falls back on the generic term object or something like that. That is, in our unit tests.. To really diagnose this, we need a small repo that allows us to debug the effect.
I tried running the provided example, which reproduces the described behavior.
When running in release mode, the StackFrame from new StackTrace(true).GetFrames() references the "wrong" line number.
That is, it is not guaranteed to return the exactly matching line number from the source file, see https://blogs.msdn.microsoft.com/jmstall/2005/03/20/caveats-about-system-diagnostics-stacktrace/
Here's an example where I inserted some dummy statements, that cannot be optimized away, to separate the assertions by at least one line.
```c#
using (new Execution.AssertionScope())
{
a.Should().BeTrue();
Console.WriteLine();
b.Should().BeTrue();
Console.WriteLine();
c.Should().BeTrue();
}
I get
```c#
Expected boolean to be true, but found False.
Expected boolean to be true, but found False.
Expected c to be true, but found False.
Unless we can in some way detect that the stack frames are crippled by the compiler, I don't think there's much we can do.
I'll close this for now, if anyone comes it with an idea for an improvement, feel to open a new issue.
Most helpful comment
Unless we can in some way detect that the stack frames are crippled by the compiler, I don't think there's much we can do.