使用 Rhino 从模拟对象引发事件
本文关键字:事件 对象 模拟 Rhino 使用 | 更新日期: 2023-09-27 17:56:35
我在模拟对象上引发事件时遇到问题。我正在使用犀牛模拟3.4。我研究过类似的问题,但未能重现任何建议的解决方案。
我有一个类 - Foo- 它有一个私有方法,只能通过注入接口的事件调用来访问 - IBar。
如何从 RhinoMock 对象引发事件 IBar.BarEvent,以便我可以在 Foo 中测试该方法?
这是我的代码:
[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; }
}
我认为是这样的:
bar.Raise(x => x.BarEvent += null, this, EventArgs.Empty);
http://ayende.com/wiki/Rhino+Mocks+3.5.ashx#Howtoraiseevents
你需要一个IEventRaiser
,你可以通过
bar.BarEvent += null;
var eventRaiser = LastCall.IgnoreArguments().GetEventRaiser();
然后,当您想要引发事件时,您可以使用所需的参数调用eventRaiser.Raise
,例如发送方和事件参数(取决于您的事件处理程序定义)。
(编辑:这是基于Rhino.Mocks 3.1!)