首页 > 解决方案 > Selenium - 在多个 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();
    }
}

标签: seleniumselenium-webdrivertestng

解决方案


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

不管怎样,如果你想在多个测试中使用这个字符串,你需要一个对它的引用,即value_test类应该有一个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 每个测试都应该有一个明确的结果,这样你就可以明确地知道一个测试用例的结果。请务必阅读 Asserts,TestNG 提供了很多可能性。

PPS 测试的名称也应该更具描述性,并且应该准确地描述它正在测试的内容。


推荐阅读