Search code examples
c#selenium-webdrivernunitpageobjects

How to initialize an instance variable (declared in a test fixture in nunit) every time before each test method(contained in the same test fixture)?


I have 3 nunit test cases under the same test fixture in vs2015. When I run the test cases individually, they pass. But when I run them together the 1st test case passes, the others fail.

Because I have an instance variable, i,e a c# property in the testfixture, that gets initialized before the first test case executes. This gets initialized only before the first test case runs, I want this property to be initialized before the start of every test case. But what's happening is - it gets initialized once brfore 1st test case runs, the same value gets used for the 2nd and 3rd test case. Thus my 2nd and 3rd test cases fail.

How do I do it?

In the below code - Page is the c# property - that performs login, clicks on the appropriate link after logging in and takes you to the target page.

Here's the code,

[TestFixture]
public class SecurityUserMgmtTests
{
    private SecurityUserManagementPage _page;
    protected override SecurityUserManagementPage Page
    {
        get
        {
            if (_page == null)
            {
                _page = new LoginPage().LoginasAdmin().GoToSecurityUserMgmtPage();
            }

            return _page;
        }
    }

    [Test]
    public void Test_ChooseARole()
    {
        Page.ChooseSecurityRole("administrator", "NMD");

    }

    [Test]
    public void Validate_if_submitting_form_without_securityrole_results_in_alertpopup()
    {
        Page.FillinLoginDetails("testuserr9", "2018/10/06", "yassds", "Ardaa");
        Page.ClickSubmit();
        var alertText = alert.Text;
        alert.Dismiss();

        Assert.AreEqual("Please select a Role for this user", alertText);
    }


    [Test]
    public void Validate_if_creating_adminuser_with_existing_username_results_in_css_alert()
    {
        Page.ChooseSecurityRole("NMD");
        Page.FillinLoginDetails("iatestuser", "2018-05-01", "yas", "Ara");
        Page.ClickSubmit();

        Assert.IsTrue(Page.GetErrorMessage().Contains("already exists"));
    }

}

Solution

  • With NUnit, you would use the SetUp attribute to define a method that will be run once per test within a test fixture. Since your Page property likely needs to be set for each run, you could go with something like this:

    [TestFixture]
    public class SecurityUserMgmtTests
    {
    
        protected override SecurityUserManagementPage Page {get;set;}
    
        [SetUp]
        public void Init() => Page = new LoginPage().LoginasAdmin().GoToSecurityUserMgmtPage();
    
        // Tests omitted
    }