2013-08-06 75 views
1

有没有办法在C#中模拟系统事件,如SystemEvents.PowerModeChanged,并在MOQ设置中人为地提高它们?使用MOQ嘲笑系统事件

+0

这是你在找什么? https://code.google.com/p/moq/wiki/QuickStart#Events –

+0

虽然该事件不属于嘲笑类型。我需要模拟的事件是SystemEvents的一部分。 – TheWolf

+2

你可以创建一个可以模拟SystemEvents的接口。非常类似于通过“IDateTimeService”模拟DateTime.Now完成的操作。 – DavidN

回答

2

不,不是直接。

我看到两种方法来实现这一点:

  1. 通过实现的systemEvent

  2. 前方的接口通过使用迂回框架如Moles FrameworkMicrosoft Fakes

3

一点点迟了,但这里是一个用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); 
     } 
    } 
}