我是JAVA和Selenium的新手,我真的很想知道为什么我的代码不起作用并抛出NullPointerException。
基本上,我想要做的是调用一个方法,该方法将WebDriver实现从不同的类调用到将作为JUnit测试执行的“Master Test”类。
但是每次执行Master Test时都会抛出NullPointerException。
这是我将要执行的主测试:
package common_methods;
import org.junit.*;
public class Master_Test extends Configurations {
@Before
public void setUp(){
try{
testConfiguration();
driver.get("http://only-testing-blog.blogspot.ro/");
} catch (Exception e){
System.out.println("setUp Exception: "+e);
}
}
@After
public void tearDown(){
driver.close();
}
@Test
public void masterTest(){
try{
TestCase1 testy1 = new TestCase1();
testy1.test1();
}catch (Exception master_e){
System.out.println("Test Exception: "+master_e);
}
}
}
现在为了更好地理解这里正在扩展的配置类:
package common_methods;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class Configurations {
public WebDriver driver;
public void testConfiguration() throws Exception{
System.setProperty("webdriver.chrome.driver", "D:\\Browser_drivers\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
}
}
这是TestCase1类,我可以从中获取我的方法:
package common_methods;
import org.openqa.selenium.*;
public class TestCase1 extends Configurations{
public void test1() throws Exception{
driver.findElement(By.id("tooltip-1")).sendKeys("Test Case 1 action");
Thread.sleep(5000);
}
}
为什么我会得到NullPointerException?
答案 0 :(得分:0)
在Master_Test,你打电话
TestCase1 testy1 = new TestCase1();
您需要传递驱动程序引用,以便它不会给出NullPointerException。此外,您需要在TestCase1类中添加构造函数来处理驱动程序。
检查以下代码。我用它与FirefoxDriver&谷歌 -
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Configurations {
public WebDriver driver;
public void testConfiguration() {
driver = new FirefoxDriver();
}
}
Master_Test
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
public class Master_Test extends Configurations {
@Before
public void setUP() {
testConfiguration();
driver.get("http://www.google.com");
}
@Test
public void masterTest() {
TestCase1 test = new TestCase1(driver);
test.test1();
}
}
TestCase1
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class TestCase1 extends Configurations {
public TestCase1(WebDriver driver) {
this.driver = driver;
}
public void test1() {
driver.findElement(By.id("lst-ib")).sendKeys("test");
}
}