Firing Events Made Easy

I have already posted about Firing Events (There is a “Fire Event” party pic to the right). Here is how to use reflective mocks to Fire Events.

Here is the example again: 

public void Example() { Button button = new Button(); button.Click += new EventHandler(button_Click); } private void button_Click(object sender, EventArgs e) { // Do Somethings here }

Now we want to test that the Example class works correctly when the button is clicked. Here is how we mimic the Button click, by mocking the Button. 

Test] public void TestThatExampleWorksWhenButtonClicked() { Mock buttonMock = MockManager.Mock(typeof(Button)); // expect Example to add an event (and keep a hook to the event) MockedEvent clickButton =buttonMock.ExpectAddEvent("Click"); // invoke our test method that registers to button.Click Example(); // Fire the event clickButton.Fire(this, EventArgs.Empty); // here we test that Example works correctly // MockManager.Verify(); }

Notice the clickButton.Fire used to fire the Click event.

Cool 🙂

Tip: The Event must be subscribed before using Fire. Guess why?

3 comments

Add Comment

Required fields are marked *. Your email address will not be published.