C#自定义事件未激发

本文关键字:事件 自定义 | 更新日期: 2023-09-27 17:57:29

我正在为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(),但结果并没有改变。怎么回事?

C#自定义事件未激发

如果测试的目的是检查事件是否被触发,那么:

  1. 将您的测试分开,分别检查每个Event
  2. 不要在初始化方法中注册事件
  3. 不要调用初始化方法中触发事件的代码
  4. 您需要注册到该事件,并在专用测试方法中触发引发该事件的代码
  5. 如果您需要同时使用ChromeFirefox测试代码,请将它们分离为不同的测试方法,这样您就可以对Chrome进行OnStartTestingOnTerminateTesting测试,对Firefox进行OnStartTestingOnTerminateTesting测试
  6. 不要依赖Console.WriteLine()进行测试,而是尝试在测试方法中创建一个标志,然后由匿名委托为特定事件设置一个事件句柄,然后在该值中设置Assert

希望它能有所帮助!