这是我得到的错误
FAILED CONFIGURATION: @BeforeTest beforetest
java.lang.NullPointerException
这是我的配置读取器类,用于加载我的属性文件
public static void Configreader() {
try {
File src = new File("./src/test/resources/config.properties");
FileInputStream fis = new FileInputStream(src);
pro = new Properties();
pro.load(fis);
System.out.println("Property class loaded");
} catch (Exception e) {
System.out.println("Exception is" +e.getMessage());
}
}
这是我要访问我的网络元素的测试班
public class LoanDetails extends Configreader {
static Properties pro;
WebDriver driver;
@BeforeTest
public void beforetest() throws Exception {
Configreader();
driver = Browser.GetBrowser();
System.out.println(" value is " +pro.getProperty("account_xpath"));
}
}
我需要访问我的网络元素(“ account_xpath”),否则一切正常
我已将我的属性文件附加到需要访问Web元素(account_xpath)的位置
答案 0 :(得分:1)
您将收到Null Pointer Exception,因为
您再次在LoanDetails类中创建了一个新的Properties类引用。 并使用它。
您的Configreader方法从不会被调用,因为Configreader类中没有testng注释,因此testng会跳过它。
解决方案-
尝试下面的代码-
package com.example;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
public class Configreader {
// make property as static
public static Properties pro;
// make method as static
public static void ConfigFileReader()
{
try {
File src = new File("./src/test/resources/config.properties");
FileInputStream fis = new FileInputStream(src);
pro = new Properties();
pro.load(fis);
System.out.println("Property class loaded");
}
catch (Exception e) {
System.out.println("Exception is" +e.getMessage());
}
}
}
package com.example;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class LoanDetails extends Configreader {
@BeforeTest
public void beforetest() throws Exception {
// Called this method in before test annotation method
ConfigFileReader();
// driver = Browser.GetBrowser();
System.out.println(pro.getProperty("account_path"));
driver.findElement(By.xpath(pro.getProperty("account_xpath"))).click();
}
@Test
void testmain() {
System.out.println("Testng test");
}
}
答案 1 :(得分:0)
出现此错误的原因是由于您在pro
类中声明了LoanDetails
变量,但未初始化任何值。因此,当您执行此操作时-
pro.getProperty("account_xpath")
由于pro
为空,它将抛出NullPointerException。
做一件事,在Configreader
类中也为account_xpath创建一个get方法,就像对“ ChromePath”和“ ApplicationURL”所做的一样,并访问该方法。
代码:
public class Configreader {
//your rest of the code
public String getAccountXPath()
{
String account_xpath = pro.getProperty("account_xpath");
return account_xpath ;
}
}
现在,在您的LoanDetails
类中,将其用作:
@BeforeTest
public void beforetest() throws Exception {
driver = Browser.GetBrowser();
driver.findElement(By.xpath(this.getAccountXPath().trim())).click();
}