1

有没有办法在 C# 中模拟系统事件,例如SystemEvents.PowerModeChanged在 MOQ 设置中人为地提高它们?

4

2 回答 2

3

有点晚了,但这里有一个在 SystemEvent 前面提到的接口的实现示例:

界面:

public interface ISystemEvents
{
    event PowerModeChangedEventHandler PowerModeChanged;
}

适配器类:

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

您在活动中的注册:

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();
      }
   }
}

测试:

[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);
         }
     }
 }
于 2017-02-13T13:57:15.783 回答
2

不,不是直接的。

我看到了两种方法来实现这一点:

  1. 通过在systemEvent前面实现一个接口

  2. 通过使用诸如Moles FrameworkMicrosoft Fakes之类的迂回框架

于 2013-08-06T22:14:23.890 回答