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);
}
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”.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With