shivam pathak
shivam pathak

Reputation: 3

Textcontext property in MStest giving null reference exeption

I am trying to create a Unit test project in Visual studio 2017 . I want to use Testcontext class prorperties like TestName and etc in my test class and Test method . But when i run the project in debug mode i get null object reference for Testcontext object .

Below is the code :

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject2
{

    [TestClass]
    public class UnitTest1
    {
        private TestContext _testcontext;
        public  TestContext Testcontext
        {
            get { return _testcontext; }
            set { _testcontext = value; }
        }

        [TestMethod]
        public void TestMethod2()
        {
            Console.WriteLine(Testcontext.TestName);
        }
    }    
}

I am not able to find out how to fix this problem using Coded UI project it works fine.

the exception

enter image description here

Upvotes: 0

Views: 2477

Answers (2)

Tanveer Badar
Tanveer Badar

Reputation: 5512

You need to change the definition for TestContext property.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject2 
{
    [TestClass]
    public class UnitTest1
    {
        public TestContext TestContext { get; set; }

        [TestMethod]
        public void TestMethod2()
        {
            Console.WriteLine(Testcontext.TestName);
        }
    }
}

Upvotes: 1

danish
danish

Reputation: 5600

You haven't set value for the _testcontext in the code sample you have provided so you will get NullReferenceException.

Upvotes: 0

Related Questions