Search code examples
c#nunittestrail

Cannot get Category value from a test case


I am trying to get the Category value of a test case. The test case has a category value of

    [TestFixture]
    [Parallelizable(ParallelScope.Self)]
    [Category("Smoke")]
    public class MSPSmokeTests : Base
    {

        [Test, TestCaseSource(nameof(LoginDataZZ3))]
        [Category("C1879186")]

In my teardown method I try to access this category value and remove the 'C' value to store it to a var variable leaving just the number '1979186.

var testCase = TestContext.CurrentContext.Test.Properties.Get("Category").ToString().Replace("C", "");

I get the following error when I run:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

NUnit.Framework.TestContext.PropertyBagAdapter.Get(...) returned null.

Is there wrong logic here or another way to do this?

The same code works in another part of the solution like so:

        [Test, TestCaseSource(nameof(LoginDataZZ3))]
        [Category("C1879186")]
        public void UserCanClickOnAdministrationTileTest(string username, string password)
        {
            LoginPage loginPage = new LoginPage(GetDriver());
            MSPDashboard mspdashboard = new MSPDashboard(GetDriver());
            driver.Value.Navigate().GoToUrl(zz3);
            loginPage.CheckCookies();
            loginPage.EnterUserNameAndPassword(username, password);
            driver.Value.Navigate().GoToUrl($"{zz3}/msp/index");
            mspdashboard.adminTile.Click();
            string currentURL = driver.Value.Url;   
            StringAssert.Contains("/msp/orgs", currentURL);
        }

Teardown method:

        [TearDown]
        public async Task TearDown()
        {

        // arrange
        RestRequest restRequest = new RestRequest($"index.php?/api/v2/get_runs/7&limit=1", Method.Get);
        string authInfo = Base64StringConverter.GetBase64String("email:password");
        restRequest.AddHeader("Authorization", "Basic " + authInfo);
        restRequest.AddHeader("Content-Type", "application/json");

        // act
        RestResponse<GetRun> response = await restClient.ExecuteAsync<GetRun>(restRequest);
        HttpStatusCode statusCode = response.StatusCode;

        // assert
        var data = JsonConvert.DeserializeObject<List<GetRun>>(response.Content);
        var a = data[0];
        var run = a.Id;

        var testCase = TestContext.CurrentContext.Test.Properties.Get("Category").ToString().Replace("C", "");
        Console.WriteLine(testCase);
        var result = TestContext.CurrentContext.Result.Outcome.Status;
        
        var testRailStatus = result switch
        {
            TestStatus.Failed => ResultStatus.Failed,
            TestStatus.Passed => ResultStatus.Passed,
            _ => ResultStatus.Retest
        };

        Console.WriteLine(testRailStatus.ToString());
        string status = testRailStatus.ToString();

        int status_id;
        if (status == "Passed")
        {
            status_id = 1;
        }
        else status_id = 5;

        Console.WriteLine(status_id);

        RestRequest addResult = new RestRequest($"index.php?/api/v2/add_result_for_case/{run}/{testCase}", Method.Post);
        addResult.AddHeader("Authorization", "Basic " + authInfo);
        addResult.AddHeader("Content-Type", "application/json");
        addResult.RequestFormat = DataFormat.Json;

        addResult.AddJsonBody(new { status_id = status_id });
        var newResponse = await restClient.ExecuteAsync(addResult);
    }

Solution

  • You are not getting category value because its not set correctly. Correct way to set category when using TestCaseSource is as below:

    [TestFixture]
    [Parallelizable(ParallelScope.Self)]
    [Category("Smoke")]
    public class MSPSmokeTests : Base
    {
    
        [Test, TestCaseSource(nameof(LoginDataZZ3), Category = "C1234")]
        public void TestMethod1(string username, string password)
        {
        }
    }
    

    Also note that [TearDown] is performed after each test method, so make sure Category is set for each TestCases else it will fail for cases where its not set.

    Update You can also add multiple categories to a test case as below:

    [Test, TestCaseSource(nameof(LoginDataZZ3), Category = "C1234, FrontEndTests")]
    

    And then can be read as:

    var categories = TestContext.CurrentContext.Test.Properties["Category"].ToList();
    Console.WriteLine(categories[0]);
    Console.WriteLine(categories[1]);