Rhino Mocks,MbUnit:检查对象是否已引发事件的最佳方法

时间:2008-09-29 14:45:19

标签: unit-testing rhino-mocks mbunit

我有一个我正在测试的对象会引发一个事件。使用Rhino Mocks检查它是否被提升的最佳方法是什么?

我能想到的最好(我确信它会比这更好):

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);
  }
}

2 个答案:

答案 0 :(得分:5)

我找到了this article by Phil Haack on how to test events using anonymous delegates

以下是代码,直接从他的博客中删除了那些懒得点击的人:

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

答案 1 :(得分:0)

我不确定您的测试实际上是如何调用DoSomething()方法的。也许你错过了一些事情来解雇这个事件。除此之外,我认为你已经在使用Rhino Mocks测试活动的正确轨道

无论如何,这是我喜欢处理事件的另一种方式:

[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);
    }
}