为什么我不能用Moq模拟MouseButtonEventArgs.GetPosition()? [英] Why can't I mock MouseButtonEventArgs.GetPosition() with Moq?
问题描述
我正在尝试使用Moq来模拟MouseButtonEventArgs.GetPosition()
,但我一直收到此错误:
I'm trying to mock MouseButtonEventArgs.GetPosition()
with Moq, but I keep receiving this error:
System.ArgumentException: Invalid setup on a non-overridable member:
m => m.GetPosition(It.IsAny<IInputElement>())
at Moq.Mock.ThrowIfCantOverride(Expression setup, MethodInfo methodInfo)
at Moq.Mock.<>c__DisplayClass12`2.<Setup>b__11()
at Moq.PexProtector.Invoke<T>(Func`1 function)
at Moq.Mock.Setup<T1,TResult>(Mock mock, Expression`1 expression)
at Moq.Mock`1.Setup<TResult>(Expression`1 expression)
这是我设置模拟程序的代码:
Here is the code where I setup my mock:
var mockMbEventArgs = new Mock<MouseButtonEventArgs>();
mockMbEventArgs.Setup(m => m.GetPosition(It.IsAny<IInputElement>())).Returns(new Point(10.0, 10.0));
我不确定自己在做什么错,有人对如何执行此操作有任何建议吗?
I'm not sure what I'm doing wrong, does anyone have any suggestions for how to do this?
推荐答案
此错误表示您正在尝试伪造未声明为 virtual 的方法.
This error means that you're trying to fake a method which is not declared as virtual.
Moq在运行时生成一个类型,以便能够伪造它,生成的类型继承自原始类型,并覆盖其虚拟方法.由于非虚拟方法不能被覆盖(这是语言的规范,这不是Moq的限制),因此无法伪造这些方法.
Moq generates a type at runtime, in order to be able to fake it the generated type inherits the from original type and overrides its virtual methods. Since non-virtual methods cannot be overridden (this is the spec of the language, it's not a limitation of Moq) it is not possible to fake these methods.
作为解决方案,您可以包装引发发送 MouseButtonEventArgs 的事件的类,并传递自己的类,该类将相关方法声明为 virtual .我认为这可能对您来说是一个小挑战,但值得尝试.
As a solution you can wrap the class that raises the event that sends MouseButtonEventArgs and pass a class of your own that declares the relevant methods as virtual. I think it might be a little challenge in your case but it's worth trying.
另一个解决方案可以是使用隔离框架,该隔离框架可以伪造非虚拟方法.例如,Typemock隔离器就是可以做到这一点的框架.隔离器使用不同的机制,因此可以伪造这种方法.
Another solution can be to use isolation framework that enables faking non-virtual methods. Typemock Isolator for example is a framework that can do this. Isolator uses different mechanism so it allows faking this kind of methods.
免责声明-我在Typemock工作
这篇关于为什么我不能用Moq模拟MouseButtonEventArgs.GetPosition()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!