使用 AutoFixture 创建谓词表达式
Create predicate expression with AutoFixture
我正在尝试以这种方式使用 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 创建谓词表达式?
它看起来像一个错误或不支持的用例。您可以通过自定义夹具来解决此问题:
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>>>();
我正在尝试以这种方式使用 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 创建谓词表达式?
它看起来像一个错误或不支持的用例。您可以通过自定义夹具来解决此问题:
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>>>();