Selenium TestNG - java.lang.NullPointerException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26032149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:10:23  来源:igfitidea点击:

Selenium TestNG - java.lang.NullPointerException

javaseleniumselenium-webdrivertestng

提问by Chamindi

I am trying to test the login function to Gmail. But it displays an exception error "java.lang.NullPointerException" . Code as follows:

我正在尝试测试 Gmail 的登录功能。但它显示异常错误 "java.lang.NullPointerException" 。代码如下:

    package gmail;

    import java.util.concurrent.TimeUnit;

    import org.junit.After;
    import org.junit.Before;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.testng.annotations.Test;

    public class Gmail {
        WebDriver driver;

        @Before 
        public void setup() {
        System.setProperty("webdriver.chrome.driver","E://chromedriver.exe");
        driver=new ChromeDriver();
        driver.get("https://accounts.google.com/");
        driver.manage().timeouts().implicitlyWait(300, TimeUnit.SECONDS);
        }

        @After
        public void quit() {
            driver.manage().deleteAllCookies();
            driver.quit();
        }

        @Test()
        public void login() {

            WebElement txtUserName=driver.findElement(By.name("Email"));
            txtUserName.sendKeys("[email protected]");

            WebElement txtPassword=driver.findElement(By.name("Passwd"));
            txtPassword.sendKeys("abcd123");

            WebElement btnLogin=driver.findElement(By.name ("signIn"));
            btnLogin.submit();
            }
    }

Error:

错误:

FAILED: login
java.lang.NullPointerException
    at gmail.Gmail.login(Gmail.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:84)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:335)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:330)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    at org.testng.TestNG.run(TestNG.java:1057)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)

=============================================== Default test

================================================ 默认测试

Tests run: 1, Failures: 1, Skips: 0

测试运行:1,失败:1,跳过:0

回答by Prashanth Sams

Your test annotations does not belongs to TestNG.

您的测试注释不属于 TestNG。

Replace

代替

@Before with @BeforeTest 
@After with @AfterTest 
@Test should point TestNG library

回答by saravan kumar

In this code snippet @Test annotation belongs to TestNg framework and @Before, @After annotation belongs to Junit framework. Eclipse will show run as TestNG test(since Test annotation is imported from TestNG library) if you run it as TestNG it wont execute @Before and @After(since they belong to Junit framework) therefore drivervariable is not initialized so we are getting NullPointer Exception

在这段代码片段中,@Test 注解属于 TestNg 框架,@Before、@After 注解属于 Junit 框架。Eclipse 将显示作为 TestNG 测试运行(因为测试注释是从 TestNG 库中导入的),如果您将其作为 TestNG 运行,它不会执行 @Before 和 @After(因为它们属于 Junit 框架)因此驱动程序变量未初始化,所以我们得到 NullPointer例外

Either we should import Junit Test annotation and run as Junit test or change @After & @Before to @AfterTest & @BeforeTest and run as TestNG test

我们应该导入 Junit Test 注释并作为 Junit 测试运行,或者将 @After & @Before 更改为 @AfterTest & @BeforeTest 并作为 TestNG 测试运行

回答by raj

package selenium;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static org.testng.Assert.assertEquals;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class Aply_login {

WebDriver d;
private By by;
    @Test
    public void aplylogin () throws BiffException, IOException, InterruptedException{

        d.get("http://multishop.orderzen.com/customer/account/login/");
        assertEquals("Customer Login | Multishop",d.getTitle());

File f = new File("F:\workspace locaiton\page object model\aplyinputs.xls");
Workbook w = Workbook.getWorkbook(f);
Sheet s = w.getSheet("Sheet1");


  for(int i=0;i<s.getRows();i++)  {    

          //User name
      d.findElement(By.id("email")).clear();    
      d.findElement(By.id("email")).sendKeys(s.getCell(0,i).getContents());
      String uname =  d.findElement(By.id("email")).getAttribute("value");  

        //Password
      d.findElement(By.id("pass")).clear();
      d.findElement(By.id("pass")).sendKeys(s.getCell(1,i).getContents());
      String pass = d.findElement(By.id("pass")).getAttribute("value"); 

        //submit
        d.findElement(By.id("send2")).click();

//Blank user name and blank password (1)
        if (uname.equals("") && pass.equals("")) {
            d.findElement(By.id("advice-required-entry-email"));
            d.findElement(By.id("advice-required-entry-pass"));
            Thread.sleep(6000);enter code here
        }
//Blank user name and valid/invalid  password (2)               
        else if(uname.equals("")){
            d.findElement(By.id("advice-required-entry-email"));
        Thread.sleep(6000);
        }   


//invalid user name blank password  (3)      
    else if(isElementPresent(d,By.xpath(".//*[@id='advice-validate-email-email']"),By.xpath(".//*[@id='advice-required-entry-pass']")))
    {
       d.findElement(By.xpath(".//*[@id='advice-validate-email-email']"));
       d.findElement(By.xpath(".//*[@id='advice-required-entry-pass']"));
       Thread.sleep(6000);
    }
//valid user name & password    (4)
    else if(isElementPresent(d,By.linkText("Log Out"))) {
        d.findElement(By.linkText("Log Out")).click();
        Thread.sleep(6000);
    }
//Invalid user & password  (5)
    else if(isElementPresent(d,By.id("advice-validate-email-email"),By.id("advice-validate-password-pass"))) {
         d.findElement(By.id("advice-validate-email-email"));   
         d.findElement(By.id("advice-validate-password-pass"));
         Thread.sleep(6000);
    }


    else if(isElementPresent(d,By.cssSelector("span..firepath-matching-node"))) {
        d.findElement(By.cssSelector("span..firepath-matching-node"));
    }   
  }



  }

private boolean isElementPresent(WebDriver d2, By linkText) {
    d.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
    try{
        d.findElement(by);
        return true;
    }
    catch(NoSuchElementException e) {
         return false;
    }
    }




private boolean isElementPresent(WebDriver d2, By xpath, By xpath2) {
    d.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);  
    try {
        d.findElement(by);
        return true;
    }
    catch(NoSuchElementException e){    

        return false;
    }

}


@BeforeMethod
    public void setUp()
    {
    // Launch browser
            d=new FirefoxDriver();
        //System.setProperty("webdriver.chrome.driver","F:\lib\chromedriver.exe");
        //d =new ChromeDriver();
    // Maximize window
    d.manage().window().maximize();
    d.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
    }
    @AfterMethod
    public void tearDown()
    {
    //  Close browser
    d.quit();
    }

    }

回答by Paras

Always check the importstatements that you are using in your code, make sure it is always the one from desired library. There can be cases where same method exits in multiple classes from different library.

始终检查import您在代码中使用的语句,确保它始终是所需库中的语句。在某些情况下,不同库的多个类中可能存在相同的方法。

Here you are using importstatements of JUnitinstead of TestNg.

在这里,您使用的import是 ofJUnit而不是 的语句TestNg

Solution:-

解决方案:-

  1. Use TestNG import statements.
  2. Use @AfterTestinstead of @Afterannotation.
  3. Use @BeforeTestinstead of @Beforeannotation.
  1. 使用 TestNG 导入语句。
  2. 使用@AfterTest代替@After注解。
  3. 使用@BeforeTest代替@Before注解。

It should help!

应该有帮助!