使用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