Mocking EventHandler

泄露秘密 提交于 2019-12-23 11:52:10

问题


Having defined an interface

 public interface IHandlerViewModel {
         EventHandler ClearInputText { get; } 
}

I would like to test if ClearInputText is invoked by some method. To do so I do something like this

SomeType obj=new SomeType();
bool clearCalled = false;
var mockHandlerViewModel=new Mock<IHandlerViewModel>();
mockHandlerViewModel.Setup(x => x.ClearInputText).Returns(delegate { clearCalled = true; });

obj.Call(mockHandlerViewModel.Object);//void Call(IHandlerViewModel);
Assert.IsTrue(clearCalled);

which fails. Simply the delegate is not called. Please help me with this.


回答1:


The example you give isn't clear. You're essentially testing your own mock.

In a scenario where the mocked proxy is passed as a dependency to an object under test, you do no set up the event handler, you Raise it.

var mockHandlerViewModel = new Mock<IHandlerViewModel>();
var objectUnderTest = new ClassUnderTestThatTakesViewModel(mockHandlerViewModel.Object);
// Do other setup... objectUnderTest should have registered an eventhandler with the mock instance. Get to a point where the mock should raise it's event..

mockHandlerViewModel.Raise(x => x.ClearInputText += null, new EventArgs());
// Next, Assert objectUnderTest to verify it did what it needed to do when handling the event.

Mocks either substitute the event source by using .Raise(), or they substitute an object that will consume another class under test's event (to assert the event was raised), in which case you use .Callback() to record "handling" the event in a local flag variable.



来源:https://stackoverflow.com/questions/13020511/mocking-eventhandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!