Selenium Web Driver 在 Edge 浏览器中的测试抛出空指针异常。

huangapple go评论79阅读模式
英文:

Selenium web driver test in Edge browser throws null pointer exception

问题

在使用Java中的Edge浏览器运行以下Selenium Web Driver测试时会抛出空指针异常但是该测试在Chrome浏览器上运行成功有人可以请教一下这里的问题吗

> java.lang.NullPointerException 	at
> payment.tests.BaseTest.beforeMethod(BaseTest.java:33) 	at
> sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 	at
> sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 	at
> sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 	at
> java.lang.reflect.Method.invoke(Unknown Source) 	at
> org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:135)
> 	at
> org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:64)
> 	at
> org.testng.internal.ConfigInvoker.invokeConfigurationMethod(ConfigInvoker.java:364)

testng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" thread-count="1" parallel="tests">
    <test name="RepayCalculatorTestChrome">
        <parameter name="browser" value="Chrome" />
        <packages>
            <package name="payment.tests" />
        </packages>
    </test>
    <test name="RepayCalculatorTestEdge">
        <parameter name="browser" value="Edge" />
        <packages>
            <package name="payment.tests" />
        </packages>
    </test>
</suite>

BaseTest.java

public class BaseTest {

    public WebDriver driver;
    public EdgeDriver edgeDriver;

    @BeforeMethod
    @Parameters("browser")
    public void beforeMethod(String browser) {
        String localDir = System.getProperty("user.dir");
        if (browser.equalsIgnoreCase("edge")) {
            System.setProperty("webdriver.edge.driver", localDir + "\\resources\\msedgedriver.exe");
            System.out.println("Edge Driver started...");
            edgeDriver.manage().window().maximize();
            edgeDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
            edgeDriver.get("test_url_here");
        } else if (browser.equalsIgnoreCase("chrome")) {
            System.setProperty("webdriver.chrome.driver", localDir + "\\resources\\chromedriver.exe");
            System.out.println("Chrome Driver started...");
            ChromeOptions options = new ChromeOptions();
            // options.addArguments("--headless");
            driver = new ChromeDriver(options);
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
            driver.get("test_url_here");
        }
    }

    @AfterMethod
    public void tearDown() {
        if (driver != null || edgeDriver != null) {
            driver.quit();
            System.out.println("Driver get instantiated. Quitting..");
        } else {
            System.out.println("Driver is null so nothing to do");
        }
    }
}

RepayCalculatorTest.java

public class RepayCalculatorTest extends BaseTest {

    String borrowAmount = "750000";
    String interestAmount = "2";
    String loanTerm = "30";

    @Test(enabled = true)
    public void loanRepayCalculator() throws InterruptedException {
        RepayCalculatorPage repayCalculator = new RepayCalculatorPage(driver);
        repayCalculator.setBorrowAmount(borrowAmount);
        WebElement webElement1 = driver.findElement(By.xpath("//input[@placeholder='Enter interest rate']"));
        webElement1.clear();
        repaymentCalculator.setInterestAmount(interestAmount);
        WebElement webElement2 = driver.findElement(By.xpath("//input[@placeholder='Enter loan term']"));
        webElement2.clear();
        repaymentCalculator.setLoanTerm(loanTerm);
        repaymentCalculator.getCalculateLoanPaymentBtn();
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        WebElement resultElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='calculatedresult']//div[@class='_3Kmts']//div[@class='ant-row _2kHnl']//div[contains(@class,'z-k7K ant-col-xs-24')]//p[@class='_3TRls _2fRgA']")));
        String resultText = resultElement.getText();
        System.out.println("EMI amount:" + resultText);
        Assert.assertEquals("$2,772 / month*", resultText);
    }
}
英文:

While running the below Selenium Web driver test in java for Edge browser, it throws null pointer exception. But the test runs successfully for the chrome browser, could someone please advise about the problem here ?

> java.lang.NullPointerException at
> payment.tests.BaseTest.beforeMethod(BaseTest.java:33) at
> sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
> sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
> sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
> java.lang.reflect.Method.invoke(Unknown Source) at
> org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:135)
> at
> org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:64)
> at
> org.testng.internal.ConfigInvoker.invokeConfigurationMethod(ConfigInvoker.java:364)

testng.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE suite SYSTEM &quot;http://testng.org/testng-1.0.dtd&quot;&gt;
&lt;suite name=&quot;Suite&quot; thread-count=&quot;1&quot; parallel=&quot;tests&quot; &gt;
&lt;test name=&quot;RepayCalculatorTestChrome&quot;&gt;
&lt;parameter name=&quot;browser&quot; value=&quot;Chrome&quot; /&gt;
&lt;packages&gt;
&lt;package name=&quot;payment.tests&quot; /&gt;
&lt;/packages&gt;
&lt;/test&gt;
&lt;test name=&quot;RepayCalculatorTestEdge&quot;&gt;
&lt;parameter name=&quot;browser&quot; value=&quot;Edge&quot; /&gt;
&lt;packages&gt;
&lt;package name=&quot;payment.tests&quot;/&gt;
&lt;/packages&gt;
&lt;/test&gt;
&lt;/suite&gt;

BaseTest.java

public class BaseTest {
public WebDriver driver;
public EdgeDriver edgeDriver;
@BeforeMethod
@Parameters(&quot;browser&quot;)
public void beforeMethod(String browser) {
//Check if parameter passed from TestNG is &#39;Edge&#39;
String localDir = System.getProperty(&quot;user.dir&quot;);
if(browser.equalsIgnoreCase(&quot;edge&quot;)){
//set path to msedgedriver.exe
System.setProperty(&quot;webdriver.edge.driver&quot;,localDir + &quot;\\resources\\msedgedriver.exe&quot;);
System.out.println(&quot;Edge Driver started...&quot;);
edgeDriver.manage().window().maximize();
edgeDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
edgeDriver.get(&quot;test_url_here&quot;);
}
//Check if parameter passed from Testng is &#39;chrome&#39;
else if(browser.equalsIgnoreCase(&quot;chrome&quot;)){
//set path to chromedriver.exe
System.setProperty(&quot;webdriver.chrome.driver&quot;,localDir + &quot;\\resources\\chromedriver.exe&quot;);
System.out.println(&quot;Chrome Driver started...&quot;);
ChromeOptions options = new ChromeOptions();
//options.addArguments(&quot;--headless&quot;);
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get(&quot;test_url_here&quot;);
}
}
@AfterMethod
public void tearDown() {
if (driver != null || edgeDriver !=null) {
driver.quit();
System.out.println(&quot;Driver get instantiated. Quitting..&quot;);
} else {
System.out.println(&quot;Driver is null so nothing to do&quot;);
}
}
}

RepayCalculatorTest.java

public class RepayCalculatorTest extends BaseTest {
String borrowAmount = &quot;750000&quot;;
String interestAmount = &quot;2&quot;;
String loanTerm = &quot;30&quot;;
@Test(enabled = true)
public void loanRepayCalculator() throws InterruptedException {
RepayCalculatorPage repayCalculator = new RepayCalculatorPage(driver);
repayCalculator.setBorrowAmount(borrowAmount);
WebElement webElement1 = driver.findElement(By.xpath(&quot;//input[@placeholder=&#39;Enter interest rate&#39;]&quot;));
webElement1.clear();
repaymentCalculator.setInterestAmount(interestAmount);
WebElement webElement2= driver.findElement(By.xpath(&quot;//input[@placeholder=&#39;Enter loan term&#39;]&quot;));
webElement2.clear();
repaymentCalculator.setLoanTerm(loanTerm);
repaymentCalculator.getCalculateLoanPaymentBtn();
//driver.manage().timeouts().implicitlyWait(7, TimeUnit.SECONDS);
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement resultElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(&quot;//div[@id=&#39;calculatedresult&#39;]//div[@class=&#39;_3Kmts&#39;]//div[@class=&#39;ant-row _2kHnl&#39;]//div[contains(@class,&#39;z-k7K ant-col-xs-24&#39;)]//p[@class=&#39;_3TRls _2fRgA&#39;]&quot;)));
String resultText = resultElement.getText();
System.out.println(&quot;EMI amount:&quot;+resultText);
Assert.assertEquals(&quot;$2,772 / month*&quot;, resultText);
}
}

答案1

得分: 1

首要问题:

在这里:

if(browser.equalsIgnoreCase("edge")){
    //设置msedgedriver.exe的路径
    System.setProperty("webdriver.edge.driver",localDir + "\\resources\\msedgedriver.exe");
    System.out.println("Edge Driver started...");
    edgeDriver.manage().window().maximize();
    edgeDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    edgeDriver.get("test_url_here");
}

你调用了 edgeDriver.manage(),然而 edgeDriver 字段尚未被初始化。

其次问题:

即使你修复了关于 edgeDriver 字段初始化的错误,你的测试还是使用 driver 字段。当你为 Chrome 运行时,你初始化了 driver 字段,以便你的测试正常工作。

当你为 Edge 运行代码时,你的代码初始化了 edgeDriver,而你的 driver 字段被设置为 null。由于你的测试使用了 driver 字段,而该字段被设置为 null,你会得到 NullPointerException

以下代码可能效果更好:

@BeforeMethod
@Parameters("browser")
public void beforeMethod(String browser) {
    //检查从TestNG传递的参数是否为'Edge'
    String localDir = System.getProperty("user.dir");
    if(browser.equalsIgnoreCase("edge")){
        //设置msedgedriver.exe的路径
        System.setProperty("webdriver.edge.driver",localDir + "\\resources\\msedgedriver.exe");
        System.out.println("Edge Driver started...");
        driver = new EdgeDriver();
    }
    //检查从TestNG传递的参数是否为'chrome'
    else if(browser.equalsIgnoreCase("chrome")){
        //设置chromedriver.exe的路径
        System.setProperty("webdriver.chrome.driver",localDir + "\\resources\\chromedriver.exe");
        System.out.println("Chrome Driver started...");
        ChromeOptions options = new ChromeOptions();
        //options.addArguments("--headless");
        driver = new ChromeDriver(options);
    }
    
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    driver.get("test_url_here");

}
英文:

There are few issues in your code.

First:

Here:

if(browser.equalsIgnoreCase(&quot;edge&quot;)){
    //set path to msedgedriver.exe
    System.setProperty(&quot;webdriver.edge.driver&quot;,localDir + &quot;\\resources\\msedgedriver.exe&quot;);
    System.out.println(&quot;Edge Driver started...&quot;);
    edgeDriver.manage().window().maximize();
    edgeDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    edgeDriver.get(&quot;test_url_here&quot;);
}

you call edgeDriver.manage() however edgeDriver field has not been initialized.

Second:

Even if you fix your bug with edgeDriver field initialization. Your tests work with driver field. When you run it for chrome you initialize driver field so that your tests work fine.

When you run your code for Edge, your code initializes edgeDriver leaving your driver field referring to null. Since your tests work with driver field which is left referring to null, you get NullPointerException.

This code should work better:

@BeforeMethod
@Parameters(&quot;browser&quot;)
public void beforeMethod(String browser) {
    //Check if parameter passed from TestNG is &#39;Edge&#39;
    String localDir = System.getProperty(&quot;user.dir&quot;);
    if(browser.equalsIgnoreCase(&quot;edge&quot;)){
        //set path to msedgedriver.exe
        System.setProperty(&quot;webdriver.edge.driver&quot;,localDir + &quot;\\resources\\msedgedriver.exe&quot;);
        System.out.println(&quot;Edge Driver started...&quot;);
        driver = new EdgeDriver();
    }
    //Check if parameter passed from Testng is &#39;chrome&#39;
    else if(browser.equalsIgnoreCase(&quot;chrome&quot;)){
        //set path to chromedriver.exe
        System.setProperty(&quot;webdriver.chrome.driver&quot;,localDir + &quot;\\resources\\chromedriver.exe&quot;);
        System.out.println(&quot;Chrome Driver started...&quot;);
        ChromeOptions options = new ChromeOptions();
        //options.addArguments(&quot;--headless&quot;);
        driver = new ChromeDriver(options);
    }
    
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    driver.get(&quot;test_url_here&quot;);

}

huangapple
  • 本文由 发表于 2020年8月27日 09:57:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63608045.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定