【问题标题】:Async NUnit Test Method passing post the await call异步 NUnit 测试方法通过后等待调用
【发布时间】:2019-05-15 04:10:00
【问题描述】:

我正在为异步方法编写 NUnit 测试,并使用范围报告来报告结果。一旦等待步骤 i 测试方法完成执行,链接到我的测试的 ExtentTest 就会完成,并且不再能够出于任何日志记录目的访问 ExtentTest。我的代码有什么问题吗?或者这是预期的?

这是我的测试方法:

[Test, RequiresThread]

public async Task GetList()
{
    try
    {
        ReportHelper.ExtentTestInfo("system.readResources() method is called");
        Resources resources = await system.readResources();
        ReportHelper.ExtentTestInfo("system.readResources() method finished and responded");

        //Test Assertions
    }
}

这是我的 ReportHelper 类:

public class ReportHelper
 {

      private static ExtentReports TestReportHTML = new ExtentReports();

      var htmlReporter = new ExtentV3HtmlReporter("Test_Run_Report_" + @".html");

      TestReportHTML.AttachReporter(htmlReporter);

      [ThreadStatic] private static ExtentTest _extentTest;

      _extentTest = TestReportHTML.CreateTest(testName); //testName is passed during [SetUp]

    public static void ExtentTestInfo(string testInfo)
     {
        _extentTest.Info(testInfo);
     }
 }

一旦执行了 await 调用,_extentTest 状态就会通过,在下一行我得到 _extentTest 的 NullReferenceException

【问题讨论】:

  • 您是否尝试过删除[ThreadStatic] 属性?这会停止在线程之间共享变量,但await 可能会导致代码在不同的线程上执行,这会导致您的_extentTestawait 之后为空。
  • 你在哪里打电话GetList
  • @JohanP GetList 是我的测试方法之一。更正了有问题的测试属性
  • @SimplyGed:谢谢,到目前为止,删除 [ThreadStatic] 属性为我解决了这个问题。但是如果我想并行运行我的测试(比如将来)并且每个测试都必须在自己的线程上运行,那么这将不起作用,因为所有测试都只有一个 _extentTest 可以使用。有什么建议吗?
  • @test_user 只需将 ReportHelper 设为非静态并在每个测试开始时创建一个新实例。这将允许多个测试同时运行。

标签: c# async-await nunit extentreports


【解决方案1】:

您需要删除[ThreadStatic] 属性。这会停止在线程之间共享变量,但await 可能会导致代码在不同的线程上执行剩余的代码,这会导致您的 _extentTest 在等待之后为空。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-21
    • 2017-06-01
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多