【发布时间】:2011-10-05 23:17:24
【问题描述】:
一点代码:
public interface IMyInterface
{
int GetIt();
}
public class MyImplementation : IMyInterface
{
public int GetIt()
{
return 10;
}
}
[Test]
public void Testit()
{
Method<MyImplementation>();
}
private void Method<T>()
where T : class , IMyInterface
{
var mock = new Mock<T>();
mock.Setup(m => m.GetIt()).Returns(() =>
{
return 40;
});
Assert.AreEqual(40, mock.Object.GetIt());
}
请注意,在更新 Mock 时,我使用的是泛型 T,但是由于 T 被限制为引用类型和 IMyInterface 类型,因此我可以毫无问题地设置方法。但由于某种原因,它总是失败,并调用 MyImplementation 的实际实现,而不是 Mocked 的实现。
【问题讨论】: