【问题标题】:C# Custom Event is not firedC# 自定义事件未触发
【发布时间】:2016-07-18 07:01:38
【问题描述】:

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

【问题讨论】:

  • 另外,您应该听从 Visual Studio 的建议并使用 OnStartTesting?.Invoke() 来避免事件注册和调用之间的竞争条件。
  • 感谢您的回答。不幸的是,Andras Zoltan 建议的答案没有奏效。
  • Jan Bońkowski:只是为了检查,您需要在控制台应用程序中显示此语句对吗??
  • Ashish Babu:我正在尝试在测试资源管理器的“输出”窗口中显示此语句

标签: c# selenium events delegates


【解决方案1】:

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

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

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2019-09-09
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多