java - 在 TestNG 中运行多个类

标签 java selenium testng

我正在尝试自动化一个场景,其中我想登录一次应用程序,然后进行操作而无需再次重新登录。

考虑一下,我有在特定类的 @BeforeSuite 方法中登录应用程序的代码。

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();
    }
}

我在 TestNGClass2 中有我的 @test 方法,它基本上尝试单击一些登录按钮。

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();
    }   
}

我有另一个类 TestNGClass3,它有另一个 @Test 方法,需要在 TestNGClass2 完成后运行。

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("<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9b8aabdaab899beb4b8b0b5f7bab6b4" rel="noreferrer noopener nofollow">[email protected]</a>");
        WebElement password = driver.findElement(By.id("user_password"));
        password.clear();
        password.sendKeys("sdass");

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

testng.xml文件如下:

<?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 -->

我的方法正确吗,因为当代码到达 TestNGClass2 的“登录”方法时我收到“空指针”异常?

最佳答案

我认为你只需要在 TestNGClass2TestNGClass3 中删除这一行

public static WebDriver driver;

您已经将driver存储在基类TestNGClass1中,因此当您在其他类中包含该行时,您基本上隐藏了实例化。

我还考虑将基类访问修饰符更改为protected,因为您可能不希望不是该基类子级的类访问驱动程序 >.

关于java - 在 TestNG 中运行多个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43474568/

相关文章:

java - 自定义 Jackson 对象映射器

java - 在 Objectify 中保留类文字

java - 在 JTable 中设置单元格边框

php - 如何从命令行运行用 PHP 编写的 Selenium 测试

junit - 使用testng时junit测试报告中的测试用例乱序

unit-testing - 忽略testng中的一个类

java - 是否可以制作多边形边界框?

html - 为什么我的 XPath 不能处理混合内容?

python - 如何在不被拒绝许可的情况下通过 headless 驱动程序访问站点

selenium - Selenium Grid2:并行测试同时在同一浏览器上运行