RhinoMocks - 在模拟接口上引发事件失败

时间:2013-09-05 17:42:16

标签: c# unit-testing events event-handling rhino-mocks

在试图举起Rhino Mock事件时,我收到以下错误

Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method)

这是将编译的最小示例。我认为我做得非常好。

namespace StackOverFlow
{
    using NUnit.Framework;
    using Rhino.Mocks;
    using Rhino.Mocks.Interfaces;

    public delegate void EventHandler();

    public interface IHasEvent
    {
        event EventHandler InterfaceEvent;
    }

    public class ClassUnderTest
    {
        public ClassUnderTest(IHasEvent hasEvent)
        {
            this.EventCounter = 0;
            hasEvent.InterfaceEvent += this.IncrementCounter;
        }

        public int EventCounter { get; set; }

        private void IncrementCounter()
        {
            ++this.EventCounter;
        }
    }

    [TestFixture]
    public class RhinoMockTest
    {
        [Test]
        public void TestEventRaising()
        {
            IHasEvent mocked = MockRepository.GenerateMock<IHasEvent>();

            mocked.InterfaceEvent += null;
            LastCall.IgnoreArguments(); // <- Exception here
            IEventRaiser raiser = LastCall.GetEventRaiser();

            ClassUnderTest cut = new ClassUnderTest(mocked);
            raiser.Raise();

            Assert.AreEqual(1, cut.EventCounter);
        }
    }
}

我查看了stackoverflow和互联网上的其他示例。 我无法应用这些解决方案。 我在这段代码中没有看到错误。 我如何从模拟中提出事件?

1 个答案:

答案 0 :(得分:4)

您应该尝试更新的事件提升语法:

IHasEvent mocked = MockRepository.GenerateMock<IHasEvent>();
ClassUnderTest cut = new ClassUnderTest(mocked);
mocked.Raise(m => m.InterfaceEvent += null);

Assert.AreEqual(1, cut.EventCounter);