检查类型是否在夹具中注册
Check if Type is Registered in Fixture
我正在为 AutoFixture 构建定制。我想用传入的 IFixture 注册一个 type/instance,但前提是它尚未注册。这可能吗?
也就是说,是否可以检查特定的 type/instance 是否已经注册到 AutoFixture IFixture?
我拥有的最佳解决方法是尝试调用 fixture.Create() 并捕获在类型未注册时发生的 ObjectCreationException。可以想象,这不是最优雅的解决方案,这就是为什么我在这里要求更好的解决方案。
正如@mark-seemann 在对问题的评论中回答的那样,目前这是不可能的。目前最著名的解决方案是尝试 wrap the Fixture's Create call in a try-catch and return null on the ObjectCreationException.
public static T TryCreate<T>( this IFixture @this, Type type )
{
try
{
var result = (T)new SpecimenContext( @this ).Resolve( type );
return result;
}
catch ( ObjectCreationException )
{
return default(T);
}
}
我正在为 AutoFixture 构建定制。我想用传入的 IFixture 注册一个 type/instance,但前提是它尚未注册。这可能吗?
也就是说,是否可以检查特定的 type/instance 是否已经注册到 AutoFixture IFixture?
我拥有的最佳解决方法是尝试调用 fixture.Create() 并捕获在类型未注册时发生的 ObjectCreationException。可以想象,这不是最优雅的解决方案,这就是为什么我在这里要求更好的解决方案。
正如@mark-seemann 在对问题的评论中回答的那样,目前这是不可能的。目前最著名的解决方案是尝试 wrap the Fixture's Create call in a try-catch and return null on the ObjectCreationException.
public static T TryCreate<T>( this IFixture @this, Type type )
{
try
{
var result = (T)new SpecimenContext( @this ).Resolve( type );
return result;
}
catch ( ObjectCreationException )
{
return default(T);
}
}