views:

656

answers:

2

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 our unit testing framework.

This third party component implements a couple of interfaces, but also needs to call back into our worker class using events. Our plan was to simulate the events that this 3rd party component can raise, and test that our worker class operated as expected.

Unfortunately we've run into a problem in that moq seems unable to mock out and raise events that are defined externally. Unfortunately I can't provide the code for the exact 3rd party API we're using, but we've recreated the issue using the MS Word API, and also shown how the tests work when when using a locally defined interface:

using Microsoft.Office.Interop.Word;
using Moq;
using NUnit.Framework;
using SeparateNamespace;

namespace SeparateNamespace
{
    public interface LocalInterface_Event
    {
        event ApplicationEvents4_WindowActivateEventHandler WindowActivate;
    }
}

namespace TestInteropInterfaces
{
    [TestFixture]
    public class Test
    {
        [Test]
        public void InteropExample()
        {
            // from interop
            Mock<ApplicationEvents4_Event> mockApp = new Mock<ApplicationEvents4_Event>();

            // identical code from here on...
            bool isDelegateCalled = false;

            mockApp.Object.WindowActivate += delegate { isDelegateCalled = true; };

            mockApp.Raise(x => x.WindowActivate += null, null, null);

            Assert.True(isDelegateCalled);
        }

        [Test]
        public void LocalExample()
        {
            // from local interface
            Mock<LocalInterface_Event> mockApp = new Mock<LocalInterface_Event>();

            // identical code from here on...
            bool isDelegateCalled = false;

            mockApp.Object.WindowActivate += delegate { isDelegateCalled = true; };

            mockApp.Raise(x => x.WindowActivate += null, null, null);

            Assert.True(isDelegateCalled);
        }
    }
}

Could anyone explain why raising events for the locally defined interface works but not the one imported from the 3rd party API (in this case Word)?

I have a feeling that this is to do with the fact we are talking to a COM object (via the interop assembly) but am not sure how to work around the problem.

A: 

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

Andy
+6  A: 

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 has been now been reported on the Moq issue tracker here: http://code.google.com/p/moq/issues/detail?id=226

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.

gt
Thanks - will keep an eye on the moq bug reports. We ended up just writing a simple wrapper class around the third party API, which we were then able to mock out using unit testing.
John Sibly
Thanks for tracking this down. I was encountering the same problem except it was with interfaces defined in F#. Turns out they also omit the IsSpecialName flag and run head on into this bug as well.
JaredPar