Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 553549
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T11:37:01+00:00 2026-05-13T11:37:01+00:00

We’ve been trying write unit tests for a worker class written in C#, which

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T11:37:01+00:00Added an answer on May 13, 2026 at 11:37 am

    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).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 377k
  • Answers 377k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer If $target is intended to refer to the h6.class element,… May 14, 2026 at 9:03 pm
  • Editorial Team
    Editorial Team added an answer Try to see through the ajax request what response are… May 14, 2026 at 9:03 pm
  • Editorial Team
    Editorial Team added an answer Here's the code i use for my feed, It's just… May 14, 2026 at 9:03 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.