繁体   English   中英

如何测试已以AssertWasCalled(AAA)方式注册的事件?

[英]How to test a event has been registered in AssertWasCalled(AAA) way?

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

我尝试使用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 );
}

更改

Arg<EventHandler>.Is.Anything 

Arg<EventHandler<YourEventArgTypeName>>.Is.Anything

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

public void RegisterEvent()
{
    // This overrides mock you set in test
    // Printer = new ActionClass ();
    Printer.PrintPage += Printer.ActionClass_PrintPage;
}

感谢@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.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM