使用AutoFixture创建谓词表达式

3
我正在尝试使用AutoFixture生成Expression<Predicate<T>>,具体方式如下:

var fixture = new Fixture();
var predicateExpr = _fixture.Create<Expression<Predicate<string>>>(); // 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)

现在,当我运行类似的东西时,但是将Predicate<T>替换为Func<T>,代码可以很好地工作。
var func = _fixture.Create<Expression<Func<string, bool>>>(); // no exception

此外,如果我尝试创建Predicate<T>(而不是Expression<Predicate<T>>),一切都很顺利。
var predicate = _fixture.Create<Predicate<string>>(); // no exception

这里我做错了什么?有没有办法使用AutoFixture创建谓词表达式?

你如果没有使用 AutoFixture,你会如何创建它? - Serhii Shushliapin
1个回答

2

看起来像是一个 bug 或不支持的使用情况。您可以通过夹具定制来解决此问题:

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>>>();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接