Why can't I make fun of MouseButtonEventArgs.GetPosition () using Moq?

I try to make fun of MouseButtonEventArgs.GetPosition() using Moq, but I keep getting 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 customize my layout:

  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 am doing wrong, does anyone have any suggestions on how to do this?

+2
source share
2 answers

This error means that you are trying to fake a method that is not declared as virtual.

Moq generates a type at runtime in order to be able to fake it; the generated type inherits from the original type and overrides its virtual methods. Since non-virtual methods cannot be overridden (this is a language specification, this is not a limitation of Moq), it is impossible to fake these methods.

As a solution, you can wrap a class that raises an event that dispatches MouseButtonEventArgs and passes in its own class, which declares the corresponding methods as virtual. I think this may be a problem in your case, but worth a try.

Another solution might be to use an isolation environment that allows you to fake non-virtual methods. Typemock Isolator, for example, is the foundation that can do this. The isolator uses a different mechanism, so it allows you to fake such methods.

Disclaimer - I work on Typemock

+9
source

MouseButtonEventArgs.GetPosition () is not an abstract, not a virtual method. You cannot mock it with MOQ, Rhino Mocks, or most other mocking frameworks.

This is because the structure of C # /. NET is structured: all methods are not virtual by default. Compare this to Java, where by default all methods are virtual.

I have not used it, but I understand that Type Mock will allow you to do this because it mocks, actually rewriting your code, and not just inheritance, as most other ridicules do.

+2
source

Source: https://habr.com/ru/post/900151/


All Articles