Selenium - 在多个 TestNG @Test-annotations 中使用文本字符串

Selenium - Use text string in several TestNG @Test-annotations

我有一个用 getText 抓取的文本字符串标签。 然后我想在另一个 @Test

中使用该字符串

我试过将它放在@BeforeSuite 中,但也无法正常工作?

你能帮忙吗...:)

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class values_test {

    static WebDriver driver;

    @BeforeTest
    public void setup() throws Exception {
        driver = new HandelDriver().getDriver("CHROME");
        driver.manage().window().maximize();
        driver.manage().deleteAllCookies();
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        driver.get("https://chercher.tech/selenium-webdriver-sample");

    }


    @Test (priority = 100)
     public void GetText() throws IOException {
        // fetches text from the element and stores it in text
        String text = driver.findElement(By.xpath("//li[@class='breadcrumb-item active update']")).getText();
        System.out.println("Text String is : "+ text);
    }


    @Test (priority = 101)
    public void PasteText() throws IOException {
        driver.findElement(By.xpath("//input[@id=\"exampleInputEmail1\"]")).sendKeys(text);
    }

    @AfterTest
    public void afterTest() {
        driver.close();
    }
}

看来你的GetText()方法实际上不是测试方法,而是实用方法。它可以是另一个包的一部分,但肯定需要有一个@Test 注释。您仍然可以在 BeforeTest 方法中调用它的逻辑。

无论哪种方式,如果你想在多个测试中使用这个字符串,你需要引用它,即 value_test class 应该有一个 String text 字段。我还建议使用比“文本”更具描述性的变量名称。

您仍然可以在 BeforeTest 设置中调用它,但现在您可以在何处存储获取的值。

按照:

public class values_test {

    static WebDriver driver;
    static String text;

    @BeforeTest
    public void setup() throws Exception {
        driver = new HandelDriver().getDriver("CHROME");
        driver.manage().window().maximize();
        driver.manage().deleteAllCookies();
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        driver.get("https://chercher.tech/selenium-webdriver-sample");
        GetText();
    }

    public void GetText() throws IOException {
        text = driver.findElement(By.xpath("//li[@class='breadcrumb-item active update']")).getText();
        System.out.println("Text String is : "+ text);
    }
     
    @Test (priority = 101)
    public void CanPasteTextInFirstEmailField() throws IOException {
        driver.findElement(By.xpath("//input[@id=\"exampleInputEmail1\"]")).sendKeys(text);
    }

    @Test (priority = 102)
    public void CanPasteTextInSecondEmailField() throws IOException {
        driver.findElement(By.xpath("//input[@id=\"exampleInputEmail2\"]")).sendKeys(text);
    }

PS 每个测试都应该有一个明确的结果,让你明确知道一个测试用例的结果。请务必阅读断言,TestNG 提供了大量的可能性。

PPS 测试的名称也应该更具描述性,并且应该真正准确地说明它正在测试什么。