Provide value in assertion failure message for variable expectation
When I include a class field in an assertion I sometimes see something like:
Collection {empty} should have an item matching (x.MyProperty == value(TestClassName).MyClassField)
It seems like FA attempted to read the value of the field but failed figuring out how to do that properly.
The assertion would look something like this:
var myCollection = List<boolean?>();
myCollection.Should().Contain(x => x.HasValue == MyClassFlield.HasValue)
Thanks for reporting. Which version of FA? 5.0 RC2?
And is that the actual assertion code that you used?
Think I found the same problem
`
[Test]
public void Demo()
{
var list = new List
var myNumber = 3;
list.Should().Contain(x => x == myNumber);
}
` results in
Expected list {1, 2} to have an item matching (x == value(FluentTesting.TestintFluentAssertion+<>c__DisplayClass0_0).myNumber).
at FluentAssertions.Execution.LateBoundTestFramework.Throw(String message)
at FluentAssertions.Execution.AssertionScope.FailWith(String message, Object[] args)
at FluentAssertions.Collections.SelfReferencingCollectionAssertions2.Contain(Expression1 predicate, String because, Object[] becauseArgs)
at FluentTesting.TestintFluentAssertion.Demo()
The same goes for filtering on properties like
somelist.Should().Contain(x => x.MyProperty == foo)
Ah, that's FA just trying to render a display version of the expression. Nothing more.
Does that answer your question?
It would be nice if the result showed the actual value on 'myNumber' in the example above. The same way it shows 3 when you use the following ` var list = new List { 1, 2 };
list.Should().Contain(x => x == 3);
`
Honestly, I would not know how to accomplish that.
The compiled Expression uses the value of myNumber at invocation time.
int myNumber = 1;
Expression<Func<int, bool>> act = i => i == myNumber;
act.Body.ToString; // "(i == value(Submission#16).<Submission#15>.myNumber)"
var f = act.Compile();
f(1); // true
f(2); // false
myNumber = 2;
f(1); // false
f(2); // true
If you instead make myNumber const, the Expression can utilize the constness.
const int myNumber = 1;
Expression<Func<int, bool>> act = i => i == myNumber;
act.Body.ToString; // "(i == 3)"
@sw-carlin do these answers answer your question?
Yes @jnyrup , that is the behavior I am seeing. I thought FA would be able to access the variable value for the error message but apparently it can only do that for literal values.
Or you just call list.Should().Contain(myNumber);