selenium - 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();
}
}
解决方案
看来您的 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 测试的名称也应该更具描述性,并且应该准确地描述它正在测试的内容。
推荐阅读
- typescript - 从多个对象数组生成组合
- javascript - indexof() 部分匹配问题
- android - 我可以做些什么来修复Android中工具栏的空指针错误?
- bash - 反向正则表达式模式匹配 - 如何判断哪个模式匹配结果(Bash)
- c - 是否应该在 minGW-W64 的 dirent.h 中识别 scandir()?
- python - 如何按月份名称对条形图进行排序?
- r - 在 n=20 时生成 1000 个样本来评估 Wald
- r - 根据闪亮仪表板的其他选项卡中的操作在选项卡中显示下载按钮
- keyboard-shortcuts - XFCE 键盘快捷键 Ctrl-Alt-Left
- r - 从每小时数据制作每日值的数据框