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?

19 November 2006 | .NET Tests | Comments | Print This Post

3 Responses to “Firing Events Made Easy”

  1. 1 Eli Lopian’s Blog (TypeMock) » Blog Archive » How To Isolate Future Instances 21 November 2006 @ 1:17 am

    […] Using this and the Firing Events techniques we can simulate different button sequences.  […]

  2. 2 private override » Blog Archive » Mock Objects… Firing Events 5 December 2006 @ 8:15 pm

    […] It has been long enough since I’ve made my last post, but with the recent posting from Eli’s blog about TypeMock on Firing Events when mocking/testing, I thought I would throw out my solution to this problem for those of us using NMock2. […]

  3. 3 private override » Mock Objects… Firing Events 16 May 2008 @ 10:24 pm

    […] It has been long enough since I’ve made my last post, but with the recent posting from Eli’s blog about TypeMock on Firing Events when mocking/testing, I thought I would throw out my solution to this problem for those of us using NMock2. […]

Leave a Reply

  1.  
  2.  
  3.  
Search Development and Integrity Management by Eli Lopian

Navigation

Recent Posts

Categories

Archives

Managment