It's incredibly useful once you know how, and encourages you to stop using reflection, passing magic strings as arguments, or having to use nameof().
"GetProductPage().GetProductPrice().Should().Be().LessThan(...)"
If you just want the assignments then it's simpler:
Add to the Evaluate method a test for MemberExpression and then:
The variable name is:
((MemberExpression)expr).Member.Name
The value is:
Expression.Lambda(expr).Compile().DynamicInvoke()
I like to use Jest’s toMatchObject to combine multiple assertions in a single assertion. If the assertion fails, the full object on both sides is shown in logs. You can easily debug tests that way.
The only way to make it even possible is to do some eval magic or to use a pre-processor like babel or a typescript compiler plugin.
But if you find something, Lemme know.
You can inspect the source, but functions don’t run in isolation so you cannot extract the source and run it somewhere else.
Simple example:
var x = 0;
var y = function() { x++; };
You can’t reliably execute function y with just y’s function body.Maybe if you replace the function with another by injecting code into a copy of the source, but I’m not sure if that’s even possible.
expect(width).toBeGreaterThan(0); expect(x+width).toBeLessThan(screenWidth);
When an assertion fails it will tell you: "Expected: X; Received: Y"For example:
public void CheckIsTrue(bool value, [CallerArgumentExpression("value")] string? expression = null)
{
if (!value)
{
Debug.WriteLine($"Failed: '{expression}'");
}
}
So if you call like this: CheckIsTrue(foo != bar && baz == true), when the value is false it prints "Failed: 'foo != bar && baz == true'".[1] https://learn.microsoft.com/en-us/dotnet/csharp/language-ref... [2] https://learn.microsoft.com/en-us/dotnet/csharp/language-ref...
test <@ width > 0 && x + width < screenWidth @>
And part of the output is: width > 0 && x + width < screenWidth
500 > 0 && x + width < screenWidth
true && x + width < screenWidth
true && 1500 + 500 < 1920
true && 2000 < 1920
true && false
false
[0]: https://github.com/SwensenSoftware/unquote
So essentially you could write
And you would get: It used Expression<T> to do the magic. Amazing debug messages. No moralizing required.This was a huge boon for us as it was a legacy codebase and we ran tens of thousands of automated tests and it was really difficult to figure out why they failed.