Search code examples
c#async-awaitnunitextentreports

Async NUnit Test Method passing post the await call


I am writing NUnit Test for async methods and am using extent reporting to report the results. The ExtentTest linked to my test get completed as soon as the await step i the test method has completed execution and am no longer able to access the ExtentTest for any logging purpose. Is there any issue with my code or is this expected ?

Here is my Test method:

[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
    }
}

Here is my ReportHelper class:

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);
     }
 }

Once the await call has been executed the _extentTest status is passed and on the next line I am getting NullReferenceException for the _extentTest


Solution

  • You need to remove the [ThreadStatic] attribute. That stops the variable being shared between threads but await may cause the code to execute the remaining code on a different thread, which is causing your _extentTest to be null after the await.