簡體   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