We\'ve been trying write unit tests for a worker class written in C#, which mocks out a third party API (COM based) using moq to dynamically create the mock objects. NUnit is ou
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;
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).