How can I generate the extent report in MStest framework in Selenium c#?

Please provide me solution for that, I am unable to generate Extent report in MStest framework with selenium C#.

The underlying principles of Extent report remains the same irrespective of the framework being used (e.g. it could be MSTest/NUnit/xUnit). Based on my experience with Extent with NUnit, here is how you could generate Extent test reports with MSTest:

  1. Include the necessary packages:
  • ExtentHtmlReporter (for version 4.x) or ExtentV3HtmlReporter (for version 3.x)
  • ExtentReports
  • ExtentTest
  • MediaEntityBuilder
  1. Use the AttachReporter method (of the ExtentReports class) for attaching the reporter (e.g. htmlReporter):
var _extent = new ExtentReports();
/* Attach reporter(s) */
_extent.AttachReporter(htmlReporter);
var _extent = new ExtentReports();
/* Attach reporter(s) */
_extent.AttachReporter(htmlReporter);
  1. The intent is to add important information about the tests in the HTML report that would be generated using the Extent framework. Use the AddSystemInfo method to add relevant information in the report:

_extent.AddSystemInfo(“Browser”, “Chrome”); _extent.AddSystemInfo(“Version”, “81.0”); extent.AddSystemInfo(“os”, “Windows 10”);

  1. Call the Flush method only once for writing the report data from the buffer to the report.

_extent.Flush();

  1. The MediaEntityBuilder class in the Extent framework lets you add screenshots to logs, as the logs do not accept image paths directly. Adding screenshot from one of the blogs that I had written for creating Extent reports with NUnit

Here is the code snippet that would help you create extent report (immaterial of the test framework being used for testing):

using System;
/* Packages related to Selenium Framework */
/* Packages related to MSTest Framework */
/* Packages related to ExtentReports */
using AventStack.ExtentReports;
using AventStack.ExtentReports.Reporter;
using System.Text;
using OpenQA.Selenium.Chrome;
 
namespace POMExample
{
    [TestFixture("chrome", "86.0", "Windows 10")]
    [TestFixture("internet explorer", "11.0", "Windows 10")]
    [TestFixture("Safari", "11.0", "macOS High Sierra")]
 
    [Parallelizable(ParallelScope.All)]
 
    public class ExtentReportTests
    {
		/* Variables related to Selenium WebDriver */
        ThreadLocal<IWebDriver> driver = new ThreadLocal<IWebDriver>();
		
		/* variables used in the constructor */
        private String browser;
        private String version;
        private String os;
 
		/* Create an object of the ExtenReports class */
        public static ExtentReports _extent;
		/* Create an object of the ExtentTest class */
		/* This is used for adding detailed information about the tests being executed using the framework */
        public ExtentTest _test;
		/* Unique Test Case to distinguish between tests */
        public String TC_Name;
 
        public ExtentReportTests(String browser, String version, String os)
        {
            this.browser = browser;
            this.version = version;
            this.os = os;
        }
 
		/* This can be changed to [ClassInitialize] with other changes */
		/* Please refer NUnit vs. XUnit vs. MSTest section in https://www.lambdatest.com/blog/nunit-vs-xunit-vs-mstest/ for porting to MSTest framework */
        [OneTimeSetUp]
        protected void ExtentStart()
        {
            var path = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
            var actualPath = path.Substring(0, path.LastIndexOf("bin"));
            var projectPath = new Uri(actualPath).LocalPath;
            Directory.CreateDirectory(projectPath.ToString() + "Reports");
 
            Console.WriteLine(projectPath.ToString());
            var reportPath = projectPath + "Reports\\Index.html";
            Console.WriteLine(reportPath);
            /* For Version 3 */
            /* var htmlReporter = new ExtentV3HtmlReporter(reportPath); */
            /* For version 4 --> Creates Index.html */
            var htmlReporter = new ExtentHtmlReporter(reportPath);
            _extent = new ExtentReports();
            _extent.AttachReporter(htmlReporter);
            _extent.AddSystemInfo("Host Name", "Cloud-based Selenium Grid on LambdaTest");
            _extent.AddSystemInfo("Environment", "Test Environment");
            _extent.AddSystemInfo("UserName", "Himanshu Sheth");
            htmlReporter.LoadConfig(projectPath + "report-config.xml");
        }
 
		/* Initialization of the Selenium WebDriver */
		/* Use [TestInitialize] for MSTest */
        [SetUp]
        public void Init()
        {
			/*
			You will have to change the implementation if you are using the local WebDriver
			*/
            String username = "user-name";
            String accesskey = "access-key";
            String gridURL = "@hub.lambdatest.com/wd/hub";
 
            DesiredCapabilities capabilities = new DesiredCapabilities();
 
            capabilities.SetCapability("user", username);
            capabilities.SetCapability("accessKey", accesskey);
            capabilities.SetCapability("browserName", browser);
            capabilities.SetCapability("version", version);
            capabilities.SetCapability("platform", os);
 
            driver.Value = new RemoteWebDriver(new Uri("https://" + username + ":" + accesskey + gridURL), capabilities, TimeSpan.FromSeconds(600));
 
            System.Threading.Thread.Sleep(2000);
        }
 
		/* Should be [[TestMethod] in MSTest */
        [Test]
        public void SearchLT_Google()
        {
            String test_url = "https://www.google.com";
            String expected_PageTitle = "Most Powerful Cross Browser Testing Tool Online | LambdaTest";
            String result_PageTitle;
            Console.WriteLine("SearchLT_Google");
 
            String context_name = TestContext.CurrentContext.Test.Name + " on " + browser + " " + version + " " + os;
            TC_Name = context_name;
 
            _test = _extent.CreateTest(context_name);
 
            HomePage home_page = new HomePage(driver.Value);
            home_page.goToPage(test_url);
            home_page.test_search(search_string);
 
            SearchPage search_page = new SearchPage(driver.Value); ;
            FinalPage final_page = search_page.click_search_results();
 
            result_PageTitle = final_page.getPageTitle();
 
            final_page.load_complete();
            Assert.AreEqual(result_PageTitle, expected_PageTitle, "Search Test Passed");
        }
 
		/* This is where we close the Extent Report and flush the information i.e. writing the information from the buffer to the report */
		/* Change to [ClassCleanup] in MSTest */
        [OneTimeTearDown]
        protected void ExtentClose()
        {
            Console.WriteLine("OneTimeTearDown");
            _extent.Flush();
        }
 
		/* Change to [TestCleanup] in MSTest */
        [TearDown]
        public void Cleanup()
        {
            bool passed = TestContext.CurrentContext.Result.Outcome.Status == NUnit.Framework.Interfaces.TestStatus.Passed;
            var exec_status = TestContext.CurrentContext.Result.Outcome.Status;
            var stacktrace = string.IsNullOrEmpty(TestContext.CurrentContext.Result.StackTrace) ? ""
            : string.Format("{0}", TestContext.CurrentContext.Result.StackTrace);
            Status logstatus = Status.Pass;
            String screenShotPath, fileName;
 
            Console.WriteLine("TearDown");
 
            DateTime time = DateTime.Now;
            fileName = "Screenshot_" + time.ToString("h_mm_ss") + TC_Name + ".png";
 
			/* Have a look at how the object of ExtentTest (i.e. _test) is used for printing information related to the test execution */
			/* This remains unchanged irrespective of the test automation framework being used for execution */
            switch (exec_status)
            {
                case TestStatus.Failed:
                    logstatus = Status.Fail;
                    /* The older way of capturing screenshots */
                    screenShotPath = Capture(driver.Value, fileName);
                    /* Capturing Screenshots using built-in methods in ExtentReports 4 */
                    var mediaEntity = CaptureScreenShot(driver.Value, fileName);
                    _test.Log(Status.Fail, "Fail");
                    /* Usage of MediaEntityBuilder for capturing screenshots */  
                    _test.Fail("ExtentReport 4 Capture: Test Failed", mediaEntity);
                    /* Usage of traditional approach for capturing screenshots */
                    _test.Log(Status.Fail, "Traditional Snapshot below: " + _test.AddScreenCaptureFromPath("Screenshots\\" + fileName));
                    break;
                case TestStatus.Passed:
                    logstatus = Status.Pass;
                    /* The older way of capturing screenshots */
                    screenShotPath = Capture(driver.Value, fileName);
                    /* Capturing Screenshots using built-in methods in ExtentReports 4 */
                    mediaEntity = CaptureScreenShot(driver.Value, fileName);
                    _test.Log(Status.Pass, "Pass");
                    /* Usage of MediaEntityBuilder for capturing screenshots */
                    _test.Pass("ExtentReport 4 Capture: Test Passed", mediaEntity);
                    /* Usage of traditional approach for capturing screenshots */
                    _test.Log(Status.Pass, "Traditional Snapshot below: " + _test.AddScreenCaptureFromPath("Screenshots\\" + fileName));
                    break;
                case TestStatus.Inconclusive:
                    logstatus = Status.Warning;
                    break;
                case TestStatus.Skipped:
                    logstatus = Status.Skip;
                    break;
                default:
                    break;
            }
            _test.Log(logstatus, "Test: " + TC_Name + " Status:" + logstatus + stacktrace);
 
            try
            {
                ((IJavaScriptExecutor)driver.Value).ExecuteScript("lambda-status=" + (passed ? "passed" : "failed"));
            }
            finally
            {
                driver.Value.Quit();
            }
        }
 
		/* This method can be removed --> It demonstrates the usage of methods used in ExtentReports 3 for capturing screenshots
		*/
		/* Use CaptureScreenShot, implemented below instead */
        public static string Capture(IWebDriver driver, String screenShotName)
        {
            ITakesScreenshot ts = (ITakesScreenshot)driver;
            Screenshot screenshot = ts.GetScreenshot();
            var pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
            var actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
            var reportPath = new Uri(actualPath).LocalPath;
            Directory.CreateDirectory(reportPath + "Reports\\" + "Screenshots");
            var finalpth = pth.Substring(0, pth.LastIndexOf("bin")) + "Reports\\Screenshots\\" + screenShotName;
            var localpath = new Uri(finalpth).LocalPath;
            screenshot.SaveAsFile(localpath, ScreenshotImageFormat.Png);
            return reportPath;
        }
 
		/* This implementation remains unchanged, MediaEntityBuilder is used for capturing screenshots */
        public MediaEntityModelProvider CaptureScreenShot(IWebDriver driver, String screenShotName)
        {
            ITakesScreenshot ts = (ITakesScreenshot)driver;
            var screenshot = ts.GetScreenshot().AsBase64EncodedString;
 
            return MediaEntityBuilder.CreateScreenCaptureFromBase64String(screenshot, screenShotName).Build();
        }
    }
}

Please refer NUnit vs. XUnit vs. MSTest section in NUnit vs. XUnit vs. MSTest: Comparing Unit Testing Frameworks In C#

For help related to Extent Reports, please refer to How To Use Extent Reports With NUnit And Selenium WebDriver? section in How To Generate Test Report In NUnit?

Do let me know @vishalingale002, if you need any further information. Would be happy to help!