1

我有一个服务类和一个动作类,当事件触发时动作发生。所以测试在服务类中注册事件是很重要的。

我尝试使用 Rhino Mock 测试 RegisterEvent 函数,但我无法使测试通过,AssertWasCalled 总是失败。

如果有人能给我一些指导或文章链接,我将不胜感激。

public class ServiceClass
{
    public ActionClass Printer {set; get;}
    public void RegisterEvent()
    {
        Printer = new ActionClass ();
        Printer.PrintPage += Printer.ActionClass_PrintPage;
    }
}
public class ActionClass
{
    event PrintPageEventHandler PrintPage;
    public void ActionClass_OnAction( object sender, PrintPageEventArgs e )
    {
        // Action here.
    }
}
[Test]
public void RegisterEvent_Test()
{
    var service = new ServiceClass();

    var mockActionClass = MockRepository.GenerateMock<IActionClass>();

    service.Printer = mockActionClass;
    service.RegisterEvent();
    mockActionClass.AssertWasCalled( x => x.PrintPage += Arg<PrintPageEventHandler>.Is.Anything );
}
4

3 回答 3

1

改变

Arg<EventHandler>.Is.Anything 

Arg<EventHandler<YourEventArgTypeName>>.Is.Anything
于 2013-06-17T09:04:50.910 回答
1

您的问题出在其他地方-在RegisterEvent您创建新实例时,ActionClass该实例覆盖了在测试中模拟的一组。要使测试通过,您只需从以下位置删除该实例化行RegisterEvent

public void RegisterEvent()
{
    // This overrides mock you set in test
    // Printer = new ActionClass ();
    Printer.PrintPage += Printer.ActionClass_PrintPage;
}
于 2013-06-17T10:37:20.477 回答
0

感谢@jimmy_keen 发现了我的错误,现在有两个有效的断言。

这是一个有效的解决方案......

public class ServiceClass
{
    public IActionClass Printer {set; get;}
    public void RegisterEvent()
    {
        Printer.PrintPage += ActionClass_PrintPage;
    }
}
public class ActionClass : IActionClass 
{
    event PrintPageEventHandler PrintPage;
    public void ActionClass_PrintPage( object sender, PrintPageEventArgs e )
    {
        // Action here.
    }
}
[Test]
public void RegisterEvent_Test()
{
    var service = new ServiceClass();

    var mockActionClass = MockRepository.GenerateMock<IActionClass>();

    service.Printer = mockActionClass;
    service.RegisterEvent();
    mockActionClass.AssertWasCalled(x => x.PrintPage += Arg<PrintPageEventHandler>.Is.Anything); // This does work. Credit to @jimmy_keen
    //mockActionClass.AssertWasCalled(x => x.PrintPage += Arg<EventHandler<PrintPageEventArgs>>.Is.Anything); // Can not compile.
    mockActionClass.AssertWasCalled(x => x.PrintPage += x.ActionClass_PrintPage); // This works.
}
于 2013-06-17T11:23:37.603 回答