![](/img/trans.png)
[英]Is there a way to know in VB.NET if a handler has been registered for an event?
[英]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.