尝试使用 Mock时 Moq 出现奇怪的问题对于泛型类型
一些代码:
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 的实现。
A bit of code:
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());
}
Notice that when newing up the Mock I'm using the generic T, however since T is constrained to being a reference type and of type IMyInterface
, I can set up the methods no problem. For some reason though, it always fails, and calls the actual implementation of MyImplementation
as opposed to the Mocked one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您本质上是在模拟类方法,因此该方法必须是虚拟的。
尝试
You are essentially mocking a class method and for that the method has to be virtual.
Try