views:

702

answers:

2

I have an object that I'm testing that raises an event. What is the best way of using Rhino Mocks to check that it was raised?

Best I could come up with (I am certain it gets better than this):

public void MyCallback(object sender, EventArgs e) { _flag = true;}

[Test]
public void DoSomethingRaisesEvent() {
  _flag = false;
  using(_mocks.Record()) {
    Expect.Call(delegeate { _obj.DoSomething();});
  }
  using(_mocks.Playback()) {
    _obj = new SomethingDoer();
    _obj.SomethingWasDoneEvent += new EventHandler(MyHandler);
    Assert.IsTrue(_flag);
  }
}
A: 

I'm not sure how your test actually calls the DoSomething() Method. Maybe you're missing something to fire the event. Other than that, I think you have are on the right track for testing events with Rhino Mocks

In any case, here is another way I like to deal with events:

[Test]
public void MyEventTest()
{

    IEventRaiser eventRaiser;

    mockView = _mocks.CreateMock<IView>();
    using (_mocks.Record())
    {
      mockView.DoSomethingEvent += null;
      eventRaiser = LastCall.IgnoreArguments();
    }
    using (_mocks.Playback())
    {
       new Controller(mockView, mockModel);
       eventRaiser.Raise(mockView, EventArgs.Empty);
    }
}
casademora
I'm not sure I understand Saul, seems like here you are explicitly triggering an event. Wheras I am trying to test that the object triggered the event implicitly while doing something.
George Mauer
+3  A: 

I found this article by Phil Haack on how to test events using anonymous delegates

Here is the code, ripped directly from his blog for those too lazy to click through:

[Test]
public void SettingValueRaisesEvent()
{
    bool eventRaised = false;
    Parameter param = new Parameter("num", "int", "1");
    param.ValueChanged += 
        delegate(object sender, ValueChangedEventArgs e)
        {
            Assert.AreEqual("42", e.NewValue);
            Assert.AreEqual("1", e.OldValue);
            Assert.AreEqual("num", e.ParameterName);
            eventRaised = true;
        };
    param.Value = "42"; //should fire event.

    Assert.IsTrue(eventRaised, "Event was not raised");
}
George Mauer