Mocking system events using MOQ

485 views Asked by At

Is there a way to mock system events in C# such as SystemEvents.PowerModeChanged and artificially raise them in a MOQ setup?

2

There are 2 answers

0
Matt B-L On

No, not directly.

I see two ways to achieve this :

  1. By Implementing an interface in front of the systemEvent

  2. By using a detouring framework such as Moles Framework or the Microsoft Fakes

0
StefGriebel On

A litte bit late, but here is an example for the implementation with an interface in front of SystemEvent Matt mentioned:

Interface:

public interface ISystemEvents
{
    event PowerModeChangedEventHandler PowerModeChanged;
}

Adapter class:

public class SystemEventsAdapter : ISystemEvents
{
    public event PowerModeChangedEventHandler PowerModeChanged;
}

Your registration on the event:

public class TestClass {

   private readonly ITestService _testService;

   public TestClass(ISystemEvents systemEvents, ITestService testService) {
      _testService = testService;
      systemEvents.PowerModeChanged += OnPowerModeChanged;
   }

   private void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e)
   {
      if (e.Mode == PowerModes.Resume)
      {
          _testService.DoStuff();
      }
   }
}

Test:

[TestFixture]
public class TestClassTests
{
     private TestClass _cut;

     private Mock<ISystemEvents> _systemEventsMock;         
     private Mock<ITestService> _testServiceMock;

     [SetUp]
     public void SetUp()
     {
         _systemEventsMock = new Mock<ISystemEvents>();
         _testServiceMock = new Mock<ITestService>();

         _cut = new TestClass(
            _systemEventsMock.Object,
            _testServiceMock.Object
         );
     }

     [TestFixture]
     public class OnPowerModeChanged : TestClassTests
     {
         [Test]
         public void When_PowerMode_Resume_Should_Call_TestService_DoStuff()
         {
             _systemEventsMock.Raise(m => m.PowerModeChanged += null, new PowerModeChangedEventArgs(PowerModes.Resume));

             _testServiceMock.Verify(m => m.DoStuff(), Times.Once);
         }
     }
 }