1
有沒有辦法在C#中模擬系統事件,如SystemEvents.PowerModeChanged
,並在MOQ設置中人爲地提高它們?使用MOQ嘲笑系統事件
有沒有辦法在C#中模擬系統事件,如SystemEvents.PowerModeChanged
,並在MOQ設置中人爲地提高它們?使用MOQ嘲笑系統事件
一點點遲了,但這裏是一個用SystemEvent前面的接口實現的例子Matt Matt:
接口:
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);
}
}
}
這是你在找什麼? https://code.google.com/p/moq/wiki/QuickStart#Events –
雖然該事件不屬於嘲笑類型。我需要模擬的事件是SystemEvents的一部分。 – TheWolf
你可以創建一個可以模擬SystemEvents的接口。非常類似於通過「IDateTimeService」模擬DateTime.Now完成的操作。 – DavidN