【问题标题】:Raising an event from a mocked object using Rhino使用 Rhino 从模拟对象引发事件
【发布时间】:2011-05-17 15:09:25
【问题描述】:

我在模拟对象上引发事件时遇到问题。我正在使用 Rhino Mocks 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; } 
}

【问题讨论】:

    标签: c# unit-testing events nunit rhino-mocks


    【解决方案1】:

    我认为是这样的:

    bar.Raise(x => x.BarEvent += null, this, EventArgs.Empty);
    

    http://ayende.com/wiki/Rhino+Mocks+3.5.ashx#Howtoraiseevents

    【讨论】:

    • FWIW,他正在使用 Rhino.Mocks 3.4
    • 啊,我错过了问题中的那一点。
    【解决方案2】:

    你需要一个IEventRaiser,你可以通过它获得

    bar.BarEvent += null;
    var eventRaiser = LastCall.IgnoreArguments().GetEventRaiser();
    

    然后,当您想引发事件时,您可以使用所需的参数调用eventRaiser.Raise,例如发送者和事件参数(取决于您的事件处理程序定义)。

    (编辑:这是基于 Rhino.Mocks 3.1!)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多