在安装/使用 Maven 插件之前,所有绝对和相对路径都在 testNG 中工作。但是使用maven后,Relative Xpath不起作用。 即使我尝试了自己的相对 Xpath 但没有成功。 我使用 Eclipse IDE for JAVA、Selenium 3.141.59 。这里我分别附上了src/main/java和src/test/java的2个代码。
phpTravelsLoginPage.java
package sqa;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class phpTravelsLoginPage {
WebDriver driver;
/* Here This Below XPath works */
By MyAccount = By.xpath("/html/body/nav/div/div[2]/ul[2]/ul/li[1]/a");
By loginBtn = By.xpath("/html/body/nav/div/div[2]/ul[2]/ul/li[1]/ul/li[1]/a");
/* But Here This Below XPath works */
// By MyAccount = By.xpath("//*[@id=\"li_myaccount\"]/a");
// By loginBtn = By.xpath("//*[@id=\"li_myaccount\"]/ul/li[]/a");
public phpTravelsLoginPage(WebDriver driver)
{
this.driver = driver;
}
// CLick on MyAccount Dropdown
public void clickOnMyAccount()
{
driver.findElement(MyAccount).click();
}
// CLick on Login Dropdown button
public void clickOnLoginButton()
{
driver.findElement(loginBtn).click();
}
/* This loginToPhptravels method will be exposed to the Test Case */
public void loginToPhptravels() throws InterruptedException
{
// Click on the MyAccount Dropdown
this.clickOnMyAccount();
// Click on the Login dropdown menu
this.clickOnLoginButton();
}
}
登录测试.java
package sqa;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import sqa.phpTravelsLoginPage;
public class loginTest {
WebDriver driver;
phpTravelsLoginPage php;
@Test
public void f() throws InterruptedException {
driver.get("https://phptravels.net");
php = new phpTravelsLoginPage(driver);
php.loginToPhptravels();
}
@BeforeTest
public void beforeTest() {
System.setProperty("webdriver.gecko.driver", "D:\\geckodriver.exe");
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
driver = new FirefoxDriver();
}
@AfterTest
public void afterTest() {
}
}
POM.XML
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sqa</groupId>
<artifactId>sqa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
</dependencies>
</project>
注意:TestNG 通过“安装新软件”安装,而不是通过 maven。
最佳答案
具有绝对xpath的测试用例执行起来不太一致,建议不要使用绝对xpath,与安装maven无关。经过搜索发现下面的一些工作和 xpath 的独特匹配希望这些对你有用!
By myaccount = By.xpath(".//a[@href='https://www.phptravels.net/']/ancestor::div[2]//a[text()=' My Account ']");<br/>
By Login = By.xpath(".//a[text()=' My Account ' and @aria-expanded]/following-sibling::ul//a[text()=' Login']");
关于java - 相对 Xpath 在 Maven TestNg 中不起作用,但绝对路径有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56175792/