【发布时间】: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