具体什么时候我们需要使用Moq提供的.As
方法?
来自快速入门文档:
// implementing multiple interfaces in mock
var foo = new Mock<IFoo>();
var disposableFoo = foo.As<IDisposable>();
// now the IFoo mock also implements IDisposable :)
disposableFoo.Setup(df => df.Dispose());
但我只是不明白为什么我们要这样做。你能给我一个实际的例子吗?
最佳答案
当您需要测试实现多个接口(interface)的对象时,您可以使用As方法。
在 this示例,如果输入对象也实现 IDisposable,则测试代码具有特定行为。像这样:
public void Execute(IFoo input)
{
// do process...
IDisposable disposable = input as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
类实现:
public class ConcreteFoo: IFoo, IDisposable
{
...
}
编辑:
所需的最小起订量配置:
var foo = new Mock<IFoo>();
var disposableFoo = foo.As<IDisposable>();
disposableFoo.Setup(df => df.Dispose());
// Verify whether the Dispose() method was called
// That's true only if we use the As method from Moq.
testedClass.Execute(disposableFoo);
disposableFoo.Verify(m => m.Dispose());
关于c# - 什么时候应该使用 Moq 的 .As 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30835395/