Rhino Mocks, MbUnit: the best way to check if an object raised an event

I have an object that I'm testing that triggers an event. What is the best way to use Rhino Mocks to verify that it has been raised?

The best I could come up with (I'm sure this is getting 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); } } 
+4
source share
2 answers

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

Here is the code torn directly from his blog for those who are too lazy to click:

 [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"); } 
+5
source

I'm not sure how your test actually calls the DoSomething () method. You may be missing something to run the event. Other than that, I think you're on the right track for testing events with Rhino Mocks

Anyway, here is another way that 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); } } 
0
source

Source: https://habr.com/ru/post/1277290/


All Articles