使用TestNG运行测试方法始终失败 求助问题排查方案
TestNG Selenium自动化测试运行报错修复方案
代码存在3个直接导致运行失败的问题:
- 变量遮蔽触发空指针异常
setup()方法内声明driver、properties、inputstream时加了类型前缀,相当于创建了方法内的局部变量,类层面定义的三个成员变量始终未赋值为null。执行测试方法时调用null对象的方法,会直接抛出NullPointerException。 - Windows路径转义非法
Java字符串中\是转义字符,原代码写的文件路径包含未转义的反斜杠,会直接触发编译错误。路径可以统一替换为正斜杠/(Windows环境下Java可正常识别),或者把每个反斜杠替换为双反斜杠\\。 - 缺少必要导入(若未手动补全会编译失败)
代码用到的Selenium类、TestNG注解、IO流类都需要显式导入,缺导入语句无法通过编译。另外要注意properties文件名大小写,Linux等大小写敏感系统下大写后缀的Objects.Properties和小写后缀的Objects.properties是两个不同文件。
修正后可运行代码
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import io.github.bonigarcia.wdm.WebDriverManager; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class BaseClass { WebDriver driver; Properties properties; FileInputStream inputstream; @BeforeClass public void setup() throws IOException { WebDriverManager.chromedriver().setup(); // 直接给成员变量赋值,不要重复声明局部变量 driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().deleteAllCookies(); properties = new Properties(); // 路径替换为正斜杠,避免转义问题 inputstream = new FileInputStream("C:/Users/admin/eclipse-workspace/NiftyUAT1/src/test/java/com/pks/test/Objects.properties"); properties.load(inputstream); } @Test public void test1() { System.out.println(111); driver.get(properties.getProperty("URL")); driver.findElement(By.xpath("//input[@id='login-email']")).sendKeys(properties.getProperty("Email")); driver.findElement(By.xpath("//input[@id='login-password']")).sendKeys(properties.getProperty("Pwd")); driver.findElement(By.xpath("//button[@id='login-submit']")).click(); } }
补充说明:如果运行时仍提示URL/账号密码为null,先检查properties文件内的键名是否和代码中
getProperty()传入的字符串完全一致,注意大小写、前后空格的差异。
内容的提问来源于stack exchange,提问作者Prakash
相关产品推荐
相关产品推荐

