Mocking 3rd party callback events using moq

六月ゝ 毕业季﹏ 提交于 2019-12-03 07:13:37

Moq 'intercepts' events by detecting calls to an event's internal methods. These methods are named add_ + the event name and are 'special' in that they are non-standard C# methods. Events are somewhat like properties (get/set) and can be defined as follows:

event EventHandler MyEvent
{
    add { /* add event code */ };
    remove { /* remove event code */ };
}

If the above event was defined on an interface to be Moq'd, the following code would be used to raise that event:

var mock = new Mock<IInterfaceWithEvent>;
mock.Raise(e => e.MyEvent += null);

As it is not possible in C# to reference events directly, Moq intercepts all method calls on the Mock and tests to see if the call was to add an event handler (in the above case, a null handler is added). If so, a reference can be indirectly obtained as the 'target' of the method.

An event handler method is detected by Moq using reflection as a method beginning with the name add_ and with the IsSpecialName flag set. This extra check is to filter out method calls unrelated to events but with a name starting add_.

In the example, the intercepted method would be called add_MyEvent and would have the IsSpecialName flag set.

However, it seems that this is not entirely true for interfaces defined in interops, as although the event handler method's name starts with add_, it does not have the IsSpecialName flag set. This may be because the events are being marshalled via lower-level code to (COM) functions, rather than being true 'special' C# events.

This can be shown (following your example) with the following NUnit test:

MethodInfo interopMethod = typeof(ApplicationEvents4_Event).GetMethod("add_WindowActivate");
MethodInfo localMethod = typeof(LocalInterface_Event).GetMethod("add_WindowActivate");

Assert.IsTrue(interopMethod.IsSpecialName);
Assert.IsTrue(localMethod.IsSpecialName);

Furthermore, an interface cannot be created which inherits the from interop interface to workaround the problem, as it will also inherit the marshalled add/remove methods.

This issue was reported on the Moq issue tracker here: http://code.google.com/p/moq/issues/detail?id=226

Update:

Until this is addressed by the Moq developers, the only workaround may be to use reflection to modify the interface which seems to defeat the purpose of using Moq. Unfortunately it may be better just to 'roll your own' Moq for this case.

This issue has been fixed in Moq 4.0 (Released Aug 2011).

Can you redefine the COM interface from the 3rd party and use it with moq.

It seems your intention is to moq away the external dependency and moq isn't playing nicely with the COMInterop assembly, you should be able to open reflector and pull any interface definitions you want from the interop assembly, define the mock and run your unit tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!