Raising an event from a mocked object using Rhino
I have a problem with raising an event on 开发者_运维知识库a mocked object. I am using Rhino Mocks 3.4. I have studied similar questions, but failed to reproduce any of the suggested solutions.
I have a class -- Foo -- which have a private method, that is only accessed by event invokation by an injected interface -- IBar.
How do I raise the event IBar.BarEvent, from a RhinoMock object, so I can Test the method in Foo?
Here is my code:
[TestFixture]
public sealed class TestEventRaisingFromRhinoMocks
{
[Test]
public void Test()
{
MockRepository mockRepository = new MockRepository();
IBar bar = mockRepository.Stub<IBar>();
mockRepository.ReplayAll();
Foo foo = new Foo(bar);
//What to do, if I want invoke bar.BarEvent with value =123??
Assert.That(foo.BarValue, Is.EqualTo(123));
}
}
public class Foo
{
private readonly IBar _bar;
private int _barValue;
public Foo(IBar bar)
{
_bar = bar;
_bar.BarEvent += BarHandling;
}
public int BarValue
{
get { return _barValue; }
}
private void BarHandling(object sender, BarEventArgs args)
{
//Eventhandling here: How do I get here with a Rhino Mock object?
_barValue = args.BarValue;
}
}
public interface IBar
{
event EventHandler<BarEventArgs> BarEvent;
}
public class BarEventArgs:EventArgs
{
public BarEventArgs(int barValue)
{
BarValue = barValue;
}
public int BarValue { get; set; }
}
Something like this I think:
bar.Raise(x => x.BarEvent += null, this, EventArgs.Empty);
http://ayende.com/wiki/Rhino+Mocks+3.5.ashx#Howtoraiseevents
You need an IEventRaiser
, which you can get via
bar.BarEvent += null;
var eventRaiser = LastCall.IgnoreArguments().GetEventRaiser();
Then, when you want to raise the event, you can call eventRaiser.Raise
with the required arguments, e.g. sender and event args (depends on your event handler definition).
(Edit: this is based on Rhino.Mocks 3.1!)
精彩评论