问题
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