Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TestContext is null when it is accessed from base class's virtual method

I have a base class ScriptBase which has a virtual function called MyTestInitialize(). When I call MyTestInitialize() from derived class, then the value of testContextInstance is null. Is there any solution for this? Please help as I am new to Automation Testing. Thanks in Advance

[CodedUITest]
public class ScriptsBase
{
    public ScriptsBase()
    {   
    }

    private static TestContext bingTestContext;

    public static TestContext BingTestContext
    {
        get { return ScriptsBase.bingTestContext; }
        set { ScriptsBase.bingTestContext = value;}
    }

    #region TestInitialize
    //Use TestInitialize to run code before running each test 
    [TestInitialize()]
    public virtual void MyTestInitialize()
    {
        Browser.CloseAllBrowsers();
        BingTestContext = testContextInstance;
    }
    #endregion

    #region TestCleanup
    //Use TestCleanup to run code after each test has run
    [TestCleanup()]
    public virtual void MyTestCleanup()
    {
        PPI.HomePage = new HomePageUI();
        Browser.CloseAllBrowsers();
    }
    #endregion

    #region TestContext
    /// <summary>
    ///Gets or sets the test context which provides
    ///information about and functionality for the current test run.
    ///</summary>
    public TestContext TestContext
    {
        get
        {
            return testContextInstance;
        }
        set
        {
            testContextInstance = value;
        }
    }
    private TestContext testContextInstance;
    #endregion
}

 public class DestinationMasterTestScripts : ScriptsBase
  {
       public DestinationMasterTestScripts()
       {      
       }

       [TestInitialize()]
       public override void MyTestInitialize()
       {
           Console.WriteLine("Initialize");
           base.MyTestInitialize();
       }
   }     
like image 647
user3012888 Avatar asked Nov 20 '13 11:11

user3012888


2 Answers

Try creating a ClassInitialize method:

    private static TestContext bingTestContext

    [ClassInitialize]
    public static void ClassInit(TestContext con)
    {
      bingTestContext = con;
    }
like image 125
Jens Kloster Avatar answered Sep 27 '22 20:09

Jens Kloster


Another option is to declare the TestContext as abstract in your base class

public abstract TestContext TestContext { get; set; }

And override it in your most derived concrete class(es)

public override TestContext TestContext { get; set; }
like image 38
Nathan Avatar answered Sep 27 '22 21:09

Nathan