如果我使用Test_Will_Give_Null_Pointer_Error
方法,我会获得NullPointerException
Stack trace
FAILED: openURL
java.lang.NullPointerException
at SeleniumPracticePackage.CallUrl.**openURL**(CallUrl.java:63)
这是第driver.get(prop.getProperty("URL"));
行
调试显示prop
为null
。
如果我将下面的行添加到openURL()
代码中工作正常。
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("C:\\Users\\XXXX\\src\\URL.properties");
prop.load(fis);
错误代码
public class Test_Will_Give_Null_Pointer_Error {
WebDriver driver;
Properties prop ;
FileInputStream fis;
@BeforeTest
public void openBrowser() throws IOException
{
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("C:\\Users\\XXXX\\src\\URL.properties");
prop.load(fis);
String browserType = prop.getProperty("Browser");
//ignored Chromedriver code below
}
@Test
public void openURL() throws IOException
{
driver.get(prop.getProperty("URL"));
//ignored rest of code
}
}
下面的代码工作正常。
public class TestRunsFine {
WebDriver driver;
Properties prop ;
FileInputStream fis;
@BeforeTest
public void openBrowser() throws IOException
{
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("C:\\Users\\XXXX\\src\\URL.properties"); prop.load(fis);System.setProperty("webdriver.chrome.driver","C:\\xxxxx\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
}
@Test
public void openURL() throws IOException
{
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("C:\\Users\\xxxx\\URL.properties");
prop.load(fis);
driver.get(prop.getProperty("URL"));
}
}
问题:
openBrowser
方法实例化它们,它们的值应该转移到openURL()
方法。使用此逻辑,我使用驱动程序对象,但看不到任何NullPointerException
。NullPointerException
?答案 0 :(得分:3)
您覆盖道具全球字段:
public void openBrowser() throws IOException
{
Properties prop = new Properties(); // HERE, this is a local field
}
要将新属性分配给您需要执行的全局道具字段:
public void openBrowser() throws IOException
{
prop = new Properties(); // Assign to global field
}
请注意,这仅在您首先调用openBrowser()
时才有效,因为prop字段将不会被初始化。
您通常不应创建与全局字段同名的本地字段,因为这会非常容易地产生这类错误。
要确保只初始化字段一次(并且在想要使用它们时初始化它们)将它们设为final并在构造函数中指定它们:
private final Properties prob; // Global field
private final WebDriver driver; // Global field
public Constructor_for_your_class()
{
prop = new Properties(); // Sets the global field
FileInputStream fis = new FileInputStream("C:\\Users\\XXXX\\src\\URL.properties");
prop.load(fis);
System.setProperty("webdriver.chrome.driver","C:\\xxxxx\\chromedriver.exe");
driver = new ChromeDriver(); // Sets the global field
}
public void openURL()
{
driver // Accesses the global field
.get(prop // Accesses the global field
.getProperty("URL"));
// ...
}