gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:14:02 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com