【发布时间】:2015-11-13 00:17:59
【问题描述】:
考虑以下类:
public interface IInterface {}
public class Class : IInterface {}
public class Customization : ICustomization
{
readonly IInterface item;
public Customization() : this( new Class() ) {}
public Customization( IInterface item )
{
this.item = item;
}
public void Customize( IFixture fixture )
{
fixture.Inject( item );
var created = fixture.Create<Class>(); // Would like this to resolve as item from previous line.
}
}
我遇到的问题是IInterface 被注入,而Class 不是。有没有办法同时注入 IInterface 和 Class 以便为两者返回相同的实例?
请注意,我想使用ICustomization(或在ICustomization 内)而不是使用测试方法上的属性来执行此操作。我正在寻找对这两个类进行自定义注入。如果我使用[Frozen( Matching.ImplementedInterfaces)]Class item 作为参数,它不起作用,因为被冻结的类会覆盖ICustomization.Customize 方法中的注入值。
另外请注意,这是示例代码,而不是我如何使用它。在 xUnit 测试方法中,我希望指定为参数的 Class 实例为上述冻结的 IInstance:
public void MyTest( IInterface @interface, Class implementation )
{
Assert.Same( @interface, implementation );
}
【问题讨论】:
-
Freeze重载并没有像你想象的那样做;见the documentation。有关实现所需结果的一种相当惯用的方法,请参见 Enrico Campidoglio 的答案。另一种选择是使用 AutoFixture 自动模拟容器扩展之一,它基本上内置了这些功能。 -
道歉@MarkSeemann,我失败了。我确实看到了关于 Inject/Freeze 的其他讨论并且感到困惑。我的意思是注入而不是冻结,并相应地更新了问题。
标签: c# unit-testing autofixture