有没有办法在 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/