I'm trying to generate the Expression<Predicate<T>> with AutoFixture this way:
var fixture = new Fixture();
var predicateExpr = _fixture.Create<Expression<Predicate<string>>>(); // exception
When I run this code I get the following exception:
System.InvalidCastException
Unable to cast object of type
'System.Linq.Expressions.Expression`1[System.Func`1[System.String]]'
to type
'System.Linq.Expressions.Expression`1[System.Predicate`1[System.String]]'.
at Ploeh.AutoFixture.SpecimenFactory.Create[T](ISpecimenContext context, T seed)
at Ploeh.AutoFixture.SpecimenFactory.Create[T](ISpecimenContext context)
Now, when I run something similar, but with Predicate<T> replaced by Func<T> the code works well.
var func = _fixture.Create<Expression<Func<string, bool>>>(); // no exception
Also, all is well if I try creating Predicate<T> (instead of Expression<Predicate<T>>)
var predicate = _fixture.Create<Predicate<string>>(); // no exception
What am I doing wrong here? Is there a way that I could create predicate expressions with AutoFixture?
It looks like a bug or not supported use case. You can work around this by fixture customization:
public class PredicateCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Register(() => (Expression<Predicate<string>>) (s => true));
}
}
=====
var fixture = new Fixture();
fixture.Customize(new PredicateCustomization());
var predicateExpr = fixture.Create<Expression<Predicate<string>>>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With