簡體   English   中英

C#自定義事件未觸發

[英]C# Custom Event is not fired

我正在為Selenium Webdriver寫一個簡單的擴展庫。 我有我的“包裝”類WebDriverManager ,它定義事件委托如下:

    public delegate void OnStartEventHandler();
    public delegate void OnTerminateEventHandler();
    public delegate void OnCheckpointEventHandler();

    public event OnStartEventHandler OnStartTesting;
    public event OnTerminateEventHandler OnTerminateTesting;
    public event OnCheckpointEventHandler OnCheckpointTesting;

    /// <summary>
    /// Method that should be fired inside method with [OneTimeSetUp] attribute
    /// </summary>
    public void OnStart() { if (OnStartTesting != null) OnStartTesting(); }

    /// <summary>
    /// Method that should be fired inside method with [OneTimeTearDown] attribute
    /// </summary>
    public void OnTerminate() { if (OnTerminateTesting != null) OnTerminateTesting(); }

    /// <summary>
    /// Method that should be fired inside method with either [SetUp] or [TearDown] attribute
    /// </summary>
    public void OnCheckpoint() { if (OnCheckpointTesting != null) OnCheckpointTesting(); }

在我的目標項目中,添加對包含WebDriverManager類的庫的引用,並編寫一個簡單的方法:

    [OneTimeSetUp]
    public void SetUp()
    {
        // wdmChrome and wdmFirefox are instances of WebDriverManager
        wdmChrome.OnStartTesting += () => { Console.WriteLine("Starting testing Chrome browser"); };
        wdmFirefox.OnStartTesting += () => { Console.WriteLine("Starting testing Firefox browser"); };

        wdmChrome.OnTerminateTesting += () => { Console.WriteLine("Terminating test of Chrome browser"); };
        wdmFirefox.OnTerminateTesting += () => { Console.WriteLine("Terminating test of Firefox browser"); };

        wdmChrome.OnStart();
        wdmFirefox.OnStart();
        // other stuff that initializes webdriver
    }

    [OneTimeTearDown]
    public void TearDown()
    {
        wdmChrome.OnTerminate();
        wdmFirefox.OnTerminate();
        wdmChrome.WebDriver.Close();
        wdmFirefox.WebDriver.Close();
    }

測試被正確觸發並通過,但是在“輸出”中沒有來自委托的消息。 我還嘗試按照Visual Studio的建議將OnStart()主體更改為OnStartTesting?.Invoke() ,但結果沒有任何變化。 這是怎么回事?

如果測試的目的是檢查事件是否被觸發,則:

  1. 分開測試以單獨檢查每個Event
  2. 不要使用初始化方法注冊事件。
  3. 不要在初始化方法中調用觸發事件的代碼。
  4. 您既需要注冊該事件,又需要在專用的測試方法中觸發引發該事件的代碼。
  5. 如果您需要同時使用ChromeFirefox來測試代碼,請將它們分開以進行不同的測試,那么您將具有針對Chrome OnStartTestingOnTerminateTesting測試以及針對Firefox OnStartTestingOnTerminateTesting
  6. 不要依賴於Console.WriteLine()為你的測試,而是嘗試創建的測試方法,然后由匿名委托集中一個事件handelr特定事件,然后里面的標志Assert該值。

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM