Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to unit test events using NUnit and Moq?

I am using NUnit and Moq to test a class that has some events and I am trying to find the best way to test whether or not an event was fired. I came up with this solution but it feels kinda dirty since I have to create an interface for the test. Any way I can do the same thing with less code or not have to create an interface?

Its not that bad but I feel someone may have a better solution. Any ideas are appreciated. Thanks.

[Test]
    public void StartedAndStoppedEventsShouldFireWhenStartedAndStopped()
    {
        var mockStartedEventSubscriber = new Mock<IEventSubscriber>();
        var mockStoppedEventSubscriber = new Mock<IEventSubscriber>();

        _NetworkMonitor.Started += mockStartedEventSubscriber.Object.Handler;
        _NetworkMonitor.Stopped += mockStoppedEventSubscriber.Object.Handler;

        _NetworkMonitor.Start();
        _NetworkMonitor.Stop();

        Func<bool> func = () => { return (eNetworkMonitorStatus.Stopped == _NetworkMonitor.Status); };
        Utilities.WaitUntilTrue(func, _NetworkMonitor.Interval * 2, 10);

        _NetworkMonitor.Started -= mockStartedEventSubscriber.Object.Handler;
        _NetworkMonitor.Stopped -= mockStoppedEventSubscriber.Object.Handler;

        mockStartedEventSubscriber.Verify(h => h.Handler(_NetworkMonitor, EventArgs.Empty), Times.Once());
        mockStoppedEventSubscriber.Verify(h => h.Handler(_NetworkMonitor, EventArgs.Empty), Times.Once());
    }

    public interface IEventSubscriber
    {
        void Handler(object sender, EventArgs e);
    }
like image 406
Dusty Lau Avatar asked Jun 29 '11 22:06

Dusty Lau


People also ask

Can we use Moq with NUnit?

We will install NUnit and Moq using the Nuget package manager. Make sure that in your references, NUnit and Moq are present after installation: For running NUnit tests and exploring the tests, we need to install a visual studio extension called “NUnit 3 Test Adapter”.

Why do we use Moq in unit testing?

Moq is a mocking framework built to facilitate the testing of components with dependencies. As shown earlier, dealing with dependencies could be cumbersome because it requires the creation of test doubles like fakes. Moq makes the creation of fakes redundant by using dynamically generated types.

How do you write multiple test cases in NUnit?

Make more copies of the attribute if you want multiple cases. The data type of the values provided to the TestCase attribute should match with that of the arguments used in the actual test case.


1 Answers

This test seems easier to do without mocks. Make the test fixture double as an event subscriber.

_networkMonitor.Started += this.SetStartedFlag; // a private method which sets a flag in the test fixture.
_networkMonitor.Start();
Assert.That(StartedFlag, Is.True);
like image 95
Gishu Avatar answered Oct 24 '22 19:10

Gishu