java.lang.NullPointerException(TestNG)

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

java.lang.NullPointer Exception (TestNG)

问题

我有一个名为“BaseTest”的类,其中包含与 web driver 相关的代码,以及所有的 BeforeTest 和 AfterTest 方法。我已经在“Login”文件和“SkillsAcquisition”文件中扩展了这个类,但只有登录文件可以正常运行,而在第二个文件中出现了 NullPointer 异常。我不知道我在这里做错了什么。

我对 Selenium 和 TestNG 都很新,所以非常感谢任何帮助。

BaseTest.java

package Students;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;

public class BaseTest {

    String driverPath = "my_path_to_chromedriver";
    public String baseUrl = "some_url";

    public WebDriver driver;
    public String expected = null;
    public String actual = null;
    private boolean acceptNextAlert;

    @BeforeTest
    public void launchBrowser() {
        System.out.println("launching Chrome browser");
        System.setProperty("webdriver.chrome.driver", driverPath);
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get(baseUrl);
    }

    @AfterTest
    public void terminateBrowser() {
        driver.close();
    }

    private boolean isElementPresent(By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

    private boolean isAlertPresent() {
        try {
            driver.switchTo().alert();
            return true;
        } catch (NoAlertPresentException e) {
            return false;
        }
    }

    private String closeAlertAndGetItsText() {
        try {
            Alert alert = driver.switchTo().alert();
            String alertText = alert.getText();
            if (acceptNextAlert) {
                alert.accept();
            } else {
                alert.dismiss();
            }
            return alertText;
        } finally {
            acceptNextAlert = true;
        }
    }
}

Login.java

package Students;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Login extends BaseTest{
    
    @Test(priority = 0)
    public void login() throws InterruptedException{
        driver.findElement(By.id("Username")).clear();
        driver.findElement(By.id("Username")).sendKeys("my_username");
        driver.findElement(By.id("Password")).clear();
        driver.findElement(By.id("Password")).sendKeys("my_password");
        driver.findElement(By.id("Password")).sendKeys(Keys.RETURN);
        expected = "Expected Text";
        actual = driver.getTitle();
        Assert.assertEquals(actual, expected);    
    }
}

SkillsAcquisition.java

package Students;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

@Test
public class SkillsAcquisition extends BaseTest{

    @Test(priority = 1)
    public void addSkills() throws InterruptedException {
        System.out.println("Test reached Second file");
        WebDriverWait d = new WebDriverWait(driver, 20);            
        d.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.id("skillAquistionTab")));
        driver.findElement(By.id("skillAquistionTab")).click();
        Thread.sleep(3000);
        d.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//a[@class='add']")));
        Thread.sleep(3000);
        driver.findElement(By.xpath("//a[@class='add']")).click();        
        System.out.println("Added");
        driver.findElement(By.xpath("(//input[@type='text'])[2]")).click();
        driver.findElement(By.xpath("(//input[@type='text'])[2]")).clear();
        driver.findElement(By.xpath("(//input[@type='text'])[2]")).sendKeys("Skill1");
        driver.findElement(By.id("page-wrapper-1")).click();
        Thread.sleep(2000);
        driver.findElement(By.linkText("Skill1")).click();
        Thread.sleep(3000);
        driver.findElement(By.id("addProgramButton")).click();
        Thread.sleep(2000);
        driver.findElement(By.id("ProgramName")).clear();
        driver.findElement(By.id("ProgramName")).sendKeys("Program1");
        driver.findElement(By.id("SaveNewProgram")).click();
        Thread.sleep(2000);
        String Newprogramname = driver.findElement(By.linkText("Program1")).getText();
        String createdprogramName = "Program1";
        Assert.assertEquals(Newprogramname, createdprogramName);
        System.out.println("Program created successfully");
    }    
}

Testng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
  <test thread-count="5" name="Test">
    <classes>
      <class name="Students.Login"/>
      <class name="Students.SkillsAcquisition"/>
    </classes>
  </test>
</suite>

错误截图:
点击查看图片

英文:

I have a class "BaseTest" class where web driver-related code resides and all the BeforeTest & AfterTest methods. I've extended this method in the 'Login' file and 'SkillsAcquisition' file, but only the login file runs fine and I get NullPointer exception in the second file. I don't know what I'm doing wrong here.

I am new to Selenium and testng so any help is hugely appreciated.

BaseTest.java

package Students;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
public class BaseTest {
String driverPath = &quot;my_path_to_chromedriver&quot;;
public String baseUrl = &quot;some_url&quot;;
public WebDriver driver ; 
public String expected = null;
public String actual = null;
private boolean acceptNextAlert;
@BeforeTest
public void launchBrowser() {
System.out.println(&quot;launching Chrome browser&quot;); 
System.setProperty(&quot;webdriver.chrome.driver&quot;, driverPath);
driver= new ChromeDriver();
driver.manage().window().maximize();
driver.get(baseUrl);
}
@AfterTest
public void terminateBrowser(){
driver.close();
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}

Login.java

package Students;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Login extends BaseTest{
@Test(priority = 0)
public void login() throws InterruptedException{
driver.findElement(By.id(&quot;Username&quot;)).clear();
driver.findElement(By.id(&quot;Username&quot;)).sendKeys(&quot;my_username&quot;);
driver.findElement(By.id(&quot;Password&quot;)).clear();
driver.findElement(By.id(&quot;Password&quot;)).sendKeys(&quot;my_password&quot;);
driver.findElement(By.id(&quot;Password&quot;)).sendKeys(Keys.RETURN);
expected = &quot;Expected Text&quot;;
actual = driver.getTitle();
Assert.assertEquals(actual, expected);	
}
}

SkillsAcquisition.java

package Students;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
@Test
public class SkillsAcquisition extends BaseTest{
@Test(priority = 1)
public void addSkills() throws InterruptedException {
System.out.println(&quot;Test reached Second file&quot;);
WebDriverWait d = new WebDriverWait(driver, 20);			
d.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.id(&quot;skillAquistionTab&quot;)));
driver.findElement(By.id(&quot;skillAquistionTab&quot;)).click();
Thread.sleep(3000);
d.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath(&quot;//a[@class=&#39;add&#39;]&quot;)));
Thread.sleep(3000);
driver.findElement(By.xpath(&quot;//a[@class=&#39;add&#39;]&quot;)).click();		
System.out.println(&quot;Added&quot;);
driver.findElement(By.xpath(&quot;(//input[@type=&#39;text&#39;])[2]&quot;)).click();
driver.findElement(By.xpath(&quot;(//input[@type=&#39;text&#39;])[2]&quot;)).clear();
driver.findElement(By.xpath(&quot;(//input[@type=&#39;text&#39;])[2]&quot;)).sendKeys(&quot;Skill1&quot;);
driver.findElement(By.id(&quot;page-wrapper-1&quot;)).click();
Thread.sleep(2000);
driver.findElement(By.linkText(&quot;Skill1&quot;)).click();
Thread.sleep(3000);
driver.findElement(By.id(&quot;addProgramButton&quot;)).click();
Thread.sleep(2000);
driver.findElement(By.id(&quot;ProgramName&quot;)).clear();
driver.findElement(By.id(&quot;ProgramName&quot;)).sendKeys(&quot;Program1&quot;);
driver.findElement(By.id(&quot;SaveNewProgram&quot;)).click();
Thread.sleep(2000);
String Newprogramname = driver.findElement(By.linkText(&quot;Program1&quot;)).getText();
String createdprogramName = &quot;Program1&quot;;
Assert.assertEquals(Newprogramname,createdprogramName);
System.out.println(&quot;Program created sucessfully&quot;);
}	
}

Testng.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE suite SYSTEM &quot;https://testng.org/testng-1.0.dtd&quot;&gt;
&lt;suite name=&quot;Suite&quot;&gt;
&lt;test thread-count=&quot;5&quot; name=&quot;Test&quot;&gt;
&lt;classes&gt;
&lt;class name=&quot;Students.Login&quot;/&gt;
&lt;class name=&quot;Students.SkillsAcquisition&quot;/&gt;
&lt;/classes&gt;
&lt;/test&gt; 
&lt;/suite&gt;

Screenshot of the error.
click to view the image

答案1

得分: 0

你需要将 @BeforeTest 更改为 @BeforeMethod@BeforeTest 会在 testng.xml 中的 test 标签执行一次测试。这就是为什么你的第一个测试通过了,但第二个测试失败了。

另一个选择(仅供参考,但我确信这不是你需要的)是将你的 testng.xml 更改为:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
  <test thread-count="5" name="Test1">
    <classes>
      <class name="Students.Login"/>
    </classes>
  </test> 
  <test thread-count="5" name="Test2">
    <classes>
      <class name="Students.SkillsAcquisition"/>
    </classes>
  </test> 
</suite>

由于这里对于每个测试类都有自己的 test 标签,你的测试将会通过。

英文:

You need to change @BeforeTest to @BeforeMethod. Before test is executed once for a test tag in your testng.xml. This is why your first test passes but the second fails.

Another option (just FYI but I am sure this is not what you need) is to change your testng.xml to:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE suite SYSTEM &quot;https://testng.org/testng-1.0.dtd&quot;&gt;
&lt;suite name=&quot;Suite&quot;&gt;
  &lt;test thread-count=&quot;5&quot; name=&quot;Test1&quot;&gt;
    &lt;classes&gt;
      &lt;class name=&quot;Students.Login&quot;/&gt;
    &lt;/classes&gt;
  &lt;/test&gt; 
  &lt;test thread-count=&quot;5&quot; name=&quot;Test2&quot;&gt;
    &lt;classes&gt;
      &lt;class name=&quot;Students.SkillsAcquisition&quot;/&gt;
    &lt;/classes&gt;
  &lt;/test&gt; 
&lt;/suite&gt;

Since here you have own test tag for each of your test classes, your tests will pass.
Since here you have own test tag for each of your test cla

huangapple
  • 本文由 发表于 2020年9月1日 22:56:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63690215.html
匿名

发表评论

匿名网友

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

确定