Moq throws NullReferenceException when setting up Prism Event

-1

I'm having a weird issue when debugging a unit test in Visual Studio. As you can see in the snippet below, I am setting up the eventAggregatorMock to return myEvent.

[TestMethod]
public void MyTestMethod()
{
    var eventAggregatorMock = new Mock<IEventAggregator>();

    var myEvent = new Mock<MyEvent>(); // Class inherits from CompositePresentationEvent<>

    eventAggregatorMock
        .Setup(e => e.GetEvent<MyEvent>())
        .Returns(myEvent.Object); // NullReferenceException is thrown

    Assert.IsTrue(true);
}

The weird issue is:

  • If I run the test (Ctrl+R, T), or debug it (Ctrl+R, Ctrl+T) stepping over each line with F10, the test succeeds and no exception is thrown.
  • If I debug the test (Ctrl+R, Ctrl+T) without any break points, the Returns method suddenly fails with:

System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=Microsoft.Practices.ServiceLocation
StackTrace: at Microsoft.Practices.ServiceLocation.ServiceLocator.get_Current()

The unit test library being used is MSTest.TestFramework from Microsoft.

Any ideas on why this is happening?

EDIT: It seems that this issue is coming from MyEvent instantiation. If I add the following line to the test method, it throws that exact exception:

var myEvent = new MyEvent();
c#
visual-studio-2019
moq
prism
asked on Stack Overflow Feb 8, 2021 by wm1sr • edited Feb 8, 2021 by wm1sr

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0