【问题标题】:Create predicate expression with AutoFixture使用 AutoFixture 创建谓词表达式
【发布时间】:2016-09-23 11:56:45
【问题描述】:

我正在尝试以这种方式使用 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&lt;T&gt; 替换为 Func&lt;T&gt; 时,代码运行良好。

var func = _fixture.Create<Expression<Func<string, bool>>>(); // no exception

另外,如果我尝试创建 Predicate&lt;T&gt;(而不是 Expression&lt;Predicate&lt;T&gt;&gt;),一切都很好

var predicate = _fixture.Create<Predicate<string>>(); // no exception

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

【问题讨论】:

  • 如果没有 AutoFixture,您将如何创建它?

标签: c# .net predicate autofixture


【解决方案1】:

它看起来像一个错误或不受支持的用例。您可以通过夹具定制来解决此问题:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 2010-10-28
    • 1970-01-01
    • 2014-08-28
    相关资源
    最近更新 更多