c# - 使用 MOQ 模拟系统事件

标签 c# mocking moq systemevent

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

最佳答案

有点晚了,但这里有一个在 SystemEvent Matt 前面提到的接口(interface)实现的例子:

接口(interface):

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

关于c# - 使用 MOQ 模拟系统事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18090495/

相关文章:

python - 避免执行模拟类的 __init__

c# - 如何模拟从另一个方法调用的方法

c# - 将 Trace 方法添加到 System.Diagnostics.TraceListener

c# - 为什么在没有 new() 泛型类型约束的情况下允许 Activator.CreateInstance<T>() ?

C# Is Type in list 问题

c# - Base 52 到 decimal 反之亦然转换

unit-testing - 在 Flask 单元 pytest 中模拟 current_app

c# - 单元测试一个处于高抽象层次的方法

Moq 相当于 Rhino Mock 的 GetArgumentsForCallsMadeOn

c# - 使用最小起订量模拟静态类