执行Java+Maven的OrangeHRM登录脚本时遇TestNG包不存在错误
解决「java: package org.testng.annotation does not exist」错误及代码优化
一、核心错误排查与修复
1. 修正TestNG注解导入路径
你代码里的TestNG注解包名写错了:原导入的是org.testng.annotation,正确包名是org.testng.annotations(多了一个s)。这是导致找不到包的直接原因之一,修正后的导入语句应为:
import org.testng.annotations.BeforeClass; import org.testng.annotations.AfterClass; import org.testng.annotations.Test;
2. 验证Maven依赖配置
确保pom.xml中TestNG的依赖配置正确,6.10版本的标准配置如下,避免依赖范围错误:
<dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.10</version> <scope>test</scope> </dependency>
3. 刷新Maven依赖
执行以下操作确保依赖正确下载:
- 在IDE中点击「Reload All Maven Projects」按钮;
- 或在终端运行命令:
mvn clean install -U,强制更新依赖并重新构建项目。
4. 确认IDE的TestNG支持
- IntelliJ IDEA:在
Settings -> Plugins中搜索TestNG,确保插件已启用; - Eclipse:安装TestNG插件,并在项目构建路径中确认TestNG库已添加。
二、代码逻辑错误修正
你的代码存在driver作用域问题,会导致tearDown和testLoggingApp方法中的driver为空指针,修正后的完整代码如下:
package day1; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.BeforeClass; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; public class sele_maven { // 类级别声明driver,确保所有方法共享同一个实例 WebDriver driver; @BeforeClass public void setUp() { System.setProperty("webdriver.chrome.driver", "C:\\Users\\singh\\Downloads\\chromedriver.exe"); // 不要重新声明driver,直接给类成员变量赋值 driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login"); } @AfterClass public void tearDown() { // 增加非空判断,避免空指针异常 if (driver != null) { driver.quit(); } } @Test public void testLoggingApp() throws InterruptedException { Thread.sleep(2000); WebElement uname = driver.findElement(By.xpath("//input[@name='username']")); uname.sendKeys("Admin"); WebElement pname = driver.findElement(By.xpath("//input[@name='password']")); pname.sendKeys("admin123"); driver.findElement(By.xpath("//button[@type='submit']")).click(); } }
修正说明:
- 删除
setUp方法中重新声明的WebDriver driver,直接为类成员变量赋值,保证所有方法能访问同一个驱动实例; - 在
tearDown中添加driver非空判断,防止空指针异常。
三、进阶优化建议
- 替换
Thread.sleep()为Selenium显式等待,提升脚本稳定性:
import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import java.time.Duration; // 在testLoggingApp方法中使用 WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement uname = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@name='username']")));
- 使用WebDriverManager自动管理驱动版本,无需手动下载驱动,在
pom.xml添加依赖:
<dependency> <groupId>io.github.bonigarcia</groupId> <artifactId>webdrivermanager</artifactId> <version>5.5.3</version> <scope>test</scope> </dependency>
然后将setUp中的驱动配置替换为:
import io.github.bonigarcia.wdm.WebDriverManager; WebDriverManager.chromedriver().setup(); driver = new ChromeDriver();
内容的提问来源于stack exchange,提问作者kulpreet
相关产品推荐
相关产品推荐

