Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking EventHandler

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.

like image 462
algorytmus Avatar asked Oct 22 '12 21:10

algorytmus


1 Answers

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.

like image 124
Steve Py Avatar answered Sep 22 '22 10:09

Steve Py