我正在致力于将 Extent Reports 与 NUnit 集成到我的自动化框架中,旨在捕获详细的测试执行日志和屏幕截图。这个想法是创建一个结构化的范围报告,将其 [TestFixture] 类下的每个 [Test] 方法显示为子节点。
主要原因是捕获测试生命周期事件,例如测试开始和结束的时间,以便将这些事件记录到范围报告中。如果不将 ExtentReportManager 作为侦听器附加,它就无法挂钩这些事件,这意味着它无法将必要的详细信息或屏幕截图记录到报告中。此附件对于构建反映实际测试执行情况的动态且详细的报告至关重要。
但是,我在尝试将 ExtentReportManager 类附加为 ITestListener 时遇到了障碍。似乎 TestExecutionContext.CurrentContext.Listener 和 AddListener() 方法都不能用于此目的。我不确定我是否遗漏了一些东西,或者我是否应该对 NUnit 采取不同的方法。
public class ExtentReportManager : ITestListener
{
private readonly BaseClass baseInstance;
public ExtentReportManager(BaseClass baseInstance)
{
this.baseInstance = baseInstance;
}
public void TestStarted(ITest test)
{
// Logic to create a child node in Extent Report
var testName = test.Name;
baseInstance.CaptureScreen(testName); // Capture screenshot
// Create and log to Extent Report
}
public void TestFinished(ITestResult result)
{
// Logic to finalize the test node in Extent Report
}
// Other ITestListener methods...
}
[SetUpFixture]
public class ExtentReportSetUp
{
[OneTimeSetUp]
public void GlobalSetup()
{
// Attempt 1: Direct assignment (does not work)
// var extentReportManager = new ExtentReportManager(new BaseClass());
// TestExecutionContext.CurrentContext.Listener = extentReportManager;
// Attempt 2: AddListener (does not work)
// TestExecutionContext.AddListener(extentReportManager);
}
[OneTimeTearDown]
public void GlobalTeardown()
{
// Flush the Extent Report
}
}
尝试使用 TestExecutionContext.CurrentContext.Listener 会导致错误:“TestExecutionContext”不包含“Listener”的定义。
尝试使用 TestExecutionContext.AddListener() 会导致类似的错误,指示未定义 AddListener。
我期望通过附加 ExtentReportManager 作为侦听器,它将捕获所有测试生命周期事件并将其记录到范围报告中,从而使报告内容更丰富、更有用。
测试运行,但 ExtentReportManager 没有将任何内容记录到范围报告中,因为它没有作为侦听器附加。
ITestEventListener
是 NUnit 引擎扩展支持的接口之一。要使用它,您的代码必须采用引擎扩展的形式。
人们可以轻松地写一本关于如何编写 NUnit 引擎扩展的书(至少是一本短书)。我建议不要在这里这样做,而是查看有关该主题的 NUnit 文档。