Running multiple classes in TestNG

2019-06-01 10:54发布

问题:

I am trying to automate a scenario wherein, I want to Login once into the application & then do manipulations without having to re-login again.

Consider that, I have the code to login into the application in the @BeforeSuite method in a specific class.

public class TestNGClass1 {

    public static WebDriver driver;

    @BeforeSuite
    public static void setUp(){
        System.setProperty("webdriver.chrome.driver", "D://Softwares//chromedriver.exe");
        driver = new ChromeDriver(); 
        //driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.get("https://www.myfitnesspal.com");
    }

    @AfterSuite
    public static void close(){
        driver.close();
    }
}

I have my @test method in TestNGClass2 which basically tries to click on some login buttons.

public class TestNGClass2 extends TestNGClass1 {

    public static WebDriver driver;

    @Test
    public static void login(){
        System.out.println("Entering the searchQuery Box");
        WebElement signUpWithEmailBtn = driver.findElement(By.xpath(".//*[@id='join']/a[2]"));
        System.out.println("srchTxtBox Box");
        signUpWithEmailBtn.click();
    }   
}

I have another class TestNGClass3 which has another @Test method which needs to be run after TestNGClass2 is completed.

public class TestNGClass3 extends TestNGClass1{

public static WebDriver driver;

    @Test
    public static void signIn(){
        WebElement emailAddress = driver.findElement(By.id("user_email"));
        emailAddress.clear();
        emailAddress.sendKeys("asdsa@gmail.com");
        WebElement password = driver.findElement(By.id("user_password"));
        password.clear();
        password.sendKeys("sdass");

        WebElement continueBtn = driver.findElement(By.id("submit"));
        continueBtn.click();
    }
}

testng.xml file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
    <test name="Regression Test">
        <classes>
            <class name="com.test.TestNGClass2" />
            <class name="com.test.TestNGClass3" />
        </classes>
    </test> <!-- Test -->
</suite> <!-- Suite -->

Is my approach right, since I'm getting "Null Pointer" exception when the code reaches the 'login' method of TestNGClass2 ?

回答1:

I think you just need to get rid of this line in both your TestNGClass2 and TestNGClass3

public static WebDriver driver;

You're already storing the driver in the base class TestNGClass1, so when you have that line in your other classes, you're basically hiding the one that is instantiated.

I'd also consider changing the base class access modifier to protected since you probably don't want classes that aren't children of that base class to access the driver.