kroe761
kroe761

Reputation: 3534

TestNG - set a "global" variable so that certain tests will always fail

I'm writing Selenium UI tests for my e-commerce company. We use a test company credit card that (unfortunately) has a credit ceiling. Occasionally the credit ceiling will be reached during testing, the "user" will be given an Auth denied message, and the test will fail. I want to set a flag somewhere that, when set to true, will result in all tests using the fake credit card will fail automatically.

Here is a basic setup of my code:

Base.java

public class Base 
{    
    public WebDriver driver = null;     
    public WebDriver getDriver() 
    {
        return new ChromeDriver();
    }    
}

Page.java

public class Page extends Base 
{
    By ccField;
    By successElement;

    public Page(WebDriver driver) 
    {
        this.driver = driver;
        ccField = By.id("ccField");
        successElement = By.id("success");
    }

    public boolean sendCreditCard(String num) 
    {
        driver.findElement(ccField).sendKeys(num);
        return driver.findElement(successElement).isDisplayed();
    }

}

TestBase.java

public class TestBase extends Base 
{    
    @BeforeMethod
    public void setup() 
    {
        Base b = new Base();
        driver = b.getDriver();
    }

    @AfterMethod
    public void tearDown() 
    {
        driver.quit();
    }   
}

PageTests.java

public class PageTests extends TestBase 
{   
    Page page;
    boolean failedBecauseOfAuth = false;

    @BeforeMethod
    public void setup() 
    {
        page = new Page(driver);
    }

    @Test
    public void one() 
    {
        // Single ship (for example)
        boolean success = page.sendCreditCard("5555555555555555");
        Assert.assertTrue(success);
    }

    @Test
    public void two() 
    {
        // Multi ship (for example)
        boolean success = page.sendCreditCard("5555555555555555");
        Assert.assertTrue(success);
    }

}

Essentially, if one failed because of an auth denied error, I need two to automatically fail at the beginning of the test. The problem is, every-time I set a flag (like authFailed = false as a field of PageTests.java, and then set authFailed = true when needed) it gets reset at the beginning of the next test run.

Upvotes: 1

Views: 2375

Answers (1)

masakral
masakral

Reputation: 26

  1. You should separate authentication from other logic thus you could put it to beforeclass method. It will cause both tests to fail.

  2. You can make "two" dependent on "one". It will cause "two" to fail. Although it's not very well to do like this, you should know this feature:

    @Test(dependsOnMethods = { "one" })
    public void two() {...}
    
  3. Make authFailed static, therefore it will keep the value for every test method.

In my opinion, the preferable solution is #1, because it separates the logic. Independence is quite important, you know.

Upvotes: 1

Related Questions