【发布时间】:2016-05-31 03:41:43
【问题描述】:
我有一个界面
public interface IInterface { void DoSomething(); }
另一个界面
public interface IOtherInterface : IInterface { }
一个抽象类
public abstract class AbstractClass : IInterface
{
public void DoSomething()
{
Console.WriteLine("Got here");
}
}
我正在编写一个单元测试并伪造 IOtherInterface。抽象类已经包含了我想在单元测试中使用的有用方法。如何让我的 A.Fake<IOtherInterface>(); 继承自 AbstractClass?
这是我迄今为止尝试过的,但它不起作用 - AbstractClass.DoSomething 没有受到打击。
IOtherInterface fake = A.Fake<IOtherInterface>(builder => builder.Implements(typeof (AbstractClass)));
fake.DoSomething();
当然,如果我做这样的代理:
var abstractFake = A.Fake<AbstractClass>();
A.CallTo(() => fake.DoSomething()).Invokes(abstractFake.DoSomething);
fake.DoSomething();
...事情如我所愿。是否有内置机制来实现这一点,这样我就不需要代理 abstractFake 对象?
更新
我需要IOtherInterface,因为我有一个需要 IOtherInterface 作为依赖项的客户端类:
class Consumer
{
public Consumer(IOtherInterface otherInterface)
{
otherInterface.DoSomething();
}
}
【问题讨论】:
-
确实如此,但是
abstractFake变量的类型将是AbstractClass而不是IOtherInterface。我需要IOtherInterface。查看更新:) -
感谢您提出这个问题。从 Blair Conrad 的回答中可以看出,结果提出了两个项目问题,这很棒!
-
@AdamRalph 老实说,看到 Blair 的专业活动通过创建那些您通常看不到的项目问题让我大吃一惊。通常,即使是项目的合作者也会说“去提交一个错误”之类的。无论如何,我很高兴我间接贡献了:)
-
确实,Blair Conrad 对任何项目来说都是一笔巨大的财富!
标签: c# unit-testing mocking fakeiteasy