Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create predicate expression with AutoFixture

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?

like image 747
RaYell Avatar asked May 23 '26 13:05

RaYell


1 Answers

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>>>();
like image 135
Aleksey L. Avatar answered May 25 '26 08:05

Aleksey L.