你如何从犀牛模拟中的严格模拟事件中提出一个事件?

时间:2011-03-22 13:38:25

标签: c# nunit rhino-mocks

我想测试以下代码在引发MyEvent事件时设置Raised属性:

public interface IEventRaiser
{
    event EventHandler<Args> MyEvent;
    void DoSomething();
}

public class EventSubscriber
{
    public EventSubscriber(IEventRaiser raiser)
    {
        this.raiser = raiser;
        this.raiser.MyEvent += EventRaised;
    }

    private readonly IEventRaiser raiser;

    private void EventRaised(object sender, Args args)
    {
        raiser.DoSomething();
        Raised = true;
    }

    public bool Raised {get; private set;}
}

我正在使用以下NUnit测试代码,但事件似乎从未引发过。 EventRaised方法永远不会运行:

[TestFixture]
public class EventSubscriberTests
{
    private MockRepository mocks;
    private IEventRaiser raiser;
    private EventSubscriber target;

    [SetUp]
    public void SetUp()
    {
        mocks = new MockRepository();
        raiser = mocks.StrictMock<IEventRaiser>();
        raiser.Expect(r => r.MyEvent += null).IgnoreArguments();
        mocks.ReplayAll();

        target = new EventSubscriber(raiser);
    }

    [TearDown]
    public void TearDown()
    {
        mocks.VerifyAll();
    }

    [Test]
    public void VerifyEventIsSubscribedTo()
    {
        raiser.BackToRecord();
        raiser.Expect(r => r.DoSomething());
        raiser.Replay();

        raiser.Raise(r => r.MyEvent += null, raiser, new Args {Property = true} );

        Assert.IsTrue(target.Raised);
    }
}

如果我在提升活动之前没有添加额外的期望,这可以正常工作。但是,我似乎无法使它与它一起工作。我做错了什么?

1 个答案:

答案 0 :(得分:1)

BackToRecord方法默认清除以前的所有期望。我实际上需要使用BackToRecord(BackToRecordOptions.None)来维持以前的状态。