The Shouldly assertion library for .NET somehow knows what expression the assertion method was called on so it is able to display it into the message. I tried to find out how it works but got lost in the source code. I suspect it looks into the compiled code but I would really like to see how this happens. From the documentation
map.IndexOfValue("boo").ShouldBe(2); // -> map.IndexOfValue("boo") should be 2 but was 1
Somehow Shouldly knows the expression map.IndexOfValue("boo") and was able to display it in the test failure message. Does anyone know how this happens?
Looking at the code, that's pretty smart.
The magic is happening in the
ActualCodeTextGetterclass. First, it retrieves the line of the source code file by using the StackTrace:Once it has the name of the source code file, along with the line and offset of the statement, it's just a matter of reading directly the file:
There's a lot more logic going on to isolate precisely the statement, but in short the trick is:
Of course, it can work only if you're running it on the same machine you used to compile the code.