无法在 NUnit 测试运行器中将 ExtentReportManager 附加为 ITestListener

问题描述 投票:0回答:1

描述:

我正在致力于将 Extent Reports 与 NUnit 集成到我的自动化框架中,旨在捕获详细的测试执行日志和屏幕截图。这个想法是创建一个结构化的范围报告,将其 [TestFixture] 类下的每个 [Test] 方法显示为子节点。

主要原因是捕获测试生命周期事件,例如测试开始和结束的时间,以便将这些事件记录到范围报告中。如果不将 ExtentReportManager 作为侦听器附加,它就无法挂钩这些事件,这意味着它无法将必要的详细信息或屏幕截图记录到报告中。此附件对于构建反映实际测试执行情况的动态且详细的报告至关重要。

但是,我在尝试将 ExtentReportManager 类附加为 ITestListener 时遇到了障碍。似乎 TestExecutionContext.CurrentContext.Listener 和 AddListener() 方法都不能用于此目的。我不确定我是否遗漏了一些东西,或者我是否应该对 NUnit 采取不同的方法。

环境:

  • NUnit 版本:3.14.0
  • NUnit3TestAdapter 版本:4.5.0
  • 使用 Visual Studio 中的 NUnit Test Runner 运行测试
  • 编程语言:C#
  • 框架:Selenium WebDriver、范围报告

代码结构:

  • ExtentReportManager 类旨在实现 ITestListener。
  • BaseClass 包含 CaptureScreen、WebDriver 初始化和拆卸等方法。
  • [SetUpFixture]用于全局测试设置和拆卸。

请求指导:

  • 如何正确地将 ExtentReportManager 附加到 NUnit 测试执行,以便它侦听测试事件?
  • 是否有其他方法可以为 Visual Studio 中的 NUnit Test Runner 中运行的测试注册 ITestListener?
  • 对于在当前 NUnit 框架内无缝实现这种集成有什么建议吗?

采取的步骤:

  1. 创建了一个 ExtentReportManager 类,该类实现 ITestListener 接口来捕获测试生命周期事件。
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...
}
  1. 按照 ChatGPT 的建议,尝试使用 TestExecutionContext.CurrentContext.Listener 和 AddListener() 方法在 [SetUpFixture] 类中附加 ExtentReportManager:
[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 没有将任何内容记录到范围报告中,因为它没有作为侦听器附加。

c# .net selenium-webdriver nunit extentreports
1个回答
0
投票

ITestEventListener
是 NUnit 引擎扩展支持的接口之一。要使用它,您的代码必须采用引擎扩展的形式。

人们可以轻松地写一本关于如何编写 NUnit 引擎扩展的书(至少是一本短书)。我建议不要在这里这样做,而是查看有关该主题的 NUnit 文档

© www.soinside.com 2019 - 2024. All rights reserved.