RhinoMocks - Raising event on mocked abstract class fails

我们两清 提交于 2019-12-12 21:22:27

问题


Does anyone know how I can raise an event on a abstract class?

The test below fails on the last line. The exception I get is the following:

System.InvalidOperationException : 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).

I am able to raise the event on an interface, but not on an abstract class that implements that interface. This is using the latest build of RhinoMocks (3.6.0.0).

Thanks, Alex

    public abstract class SomeClass : SomeInterface
    {
        public event EventHandler SomeEvent;
    }

    public interface SomeInterface
    {
        event EventHandler SomeEvent;
    }

    [Test]
    public void Test_raising_event()
    {
        var someClass = MockRepository.GenerateMock<SomeClass>();
        var someInterface = MockRepository.GenerateMock<SomeInterface>();

        someInterface.Raise(x => x.SomeEvent += null, someClass, EventArgs.Empty);
        someClass.Raise(x => x.SomeEvent += null, someClass, EventArgs.Empty);
    }

回答1:


Problem is explained by exception message:

System.InvalidOperationException : 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).

Your event is not virtual, ie. Rhino won't be able to override it. Simply add virtual keyword to your abstract class event definition.

Bit background information. When you call MocksRepository.GenerateMock<SomeClass> Rhino will create dynamic proxy class, which it will use to record calls, prepare stubs and so forth. This class may look +/- like this:

public class SomeClassDynamicProxy1 : SomeClass
{
    public override EventHandler SomeEvent 
    { 
        add { ... }
        remove { ... } 
    }

    ...
}

Without virtual in your SomeClass, this code will naturaly fail as it does now.



来源:https://stackoverflow.com/questions/10795770/rhinomocks-raising-event-on-mocked-abstract-class-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!