模拟事件处理程序 [英] Mocking EventHandler

查看:83
本文介绍了模拟事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已定义接口

 public interface IHandlerViewModel {
         EventHandler ClearInputText { get; } 
}

我想测试是否通过某种方法调用ClearInputText. 为此,我要做类似的事情

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.

推荐答案

您提供的示例不清楚.您实质上是在测试自己的模拟游戏.

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.

模仿者可以使用.Raise()替换事件源,也可以替换一个对象,该对象将消耗被测事件的另一个类(以断言该事件被引发),在这种情况下,您可以使用.Callback()来记录在本地标志变量中处理"事件.

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.

这篇关于模拟事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆