黄瓜分步定义处的空指针异常
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了黄瓜分步定义处的空指针异常相关的知识,希望对你有一定的参考价值。
我正在将Cucumber BDD与TestNG一起使用,但是在我的步骤中得到了NullPointerException。
我尝试了这里建议的很多方法,但没有用。
请帮助我。我真的不确定是什么引起了错误
Runner文件是BasePage:
package main;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import com.google.common.io.Files;
import com.relevantcodes.extentreports.LogStatus;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.javascriptExecutor;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;
//import helpers.ReportHelper;
import io.cucumber.testng.TestNGCucumberRunner;
import ptest.utilities.ExtentTestManager;
import ptest.utilities.ReadExcel;
@CucumberOptions(strict = true,
monochrome = true,
features = "src/test/resources/features",
glue = "stepdefinition",
//format = {"pretty","json:target/cucumber.json"},
tags = { "@TC001" }
)
public class CucumberRunner extends AbstractTestNGCucumberTests {
public static WebDriver driver;
public WebDriverWait wait;
public static Properties prop;
public static EventFiringWebDriver e_driver;
public static WebElement webelement;
public static List<WebElement> webelements = null;
public static int defaultBrowserTimeOut = 30000;
public static List<String> windowHandlers;
public static ReadExcel readExcel;
public static WebDriver GoToURL(String browserName, String url)throws UnknownHostException {
//deleteTempFile();
if (browserName.equalsIgnoreCase("firefox")) {
System.setProperty("webdriver.gecko.driver",System.getProperty("user.dir") + "\geckodriver.exe");
/* DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
Webdriver driver = new FirefoxDriver(capabilities);*/
driver = new FirefoxDriver();
driver.get(url);
} else if (browserName.equalsIgnoreCase("iexplorer")) {
System.setProperty("webdriver.ie.driver",
System.getProperty("user.dir") + "\IEDriverServer.exe");
/* DesiredCapabilities capabilities = DesiredCapabilities.
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
capabilities.setCapability("ignoreZoomSetting", true);*/
driver = new InternetExplorerDriver();
} else if (browserName.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") +"\lib\chromedriver.exe");
driver = new ChromeDriver();
driver.get(url);
}
driver.manage().timeouts().implicitlyWait(defaultBrowserTimeOut, TimeUnit.MILLISECONDS);
driver.manage().deleteAllCookies();
if (browserName.equalsIgnoreCase("iexplorer"))
SwitchToAlert();
if (windowHandlers == null)
windowHandlers = new LinkedList<String>();
else
windowHandlers.clear();
windowHandlers.add(driver.getWindowHandle());
driver.manage().window().maximize();
return driver;
}
@BeforeMethod
public static WebDriver getDriver() {
return driver;
}
/*
* @AfterMethod public static void shutDownDriver() { if (driver != null)
* driver.quit(); }
*/
/**
* @param driver
* @param element
*/
public static void highlightElement(WebDriver driver, WebElement element) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', arguments[1]);",
element, "border: 2px solid DeepPink;");
}
/**
* @param locator in particular format mentioned
* @return WebElement
*/
public static WebElement findElement(String locator) {
//Locator Values are Expected in string format like "name==abc" or "id==pqr" or "xpath==//*[@id='uname']"
if (locator != null) {
String[] arrLocator = locator.split("==");
String locatorTag = arrLocator[0].trim();
String objectLocator = arrLocator[1].trim();
try {
if (locatorTag.equalsIgnoreCase("id")) {
webelement = driver.findElement(By.id(objectLocator));
//highlightElement(driver, webelement);
} else if (locatorTag.equalsIgnoreCase("name")) {
webelement = driver.findElement(By.name(objectLocator));
//highlightElement(driver, webelement);
} else if (locatorTag.equalsIgnoreCase("xpath")) {
webelement = driver.findElement(By.xpath(objectLocator));
//highlightElement(driver, webelement);
} else if (locatorTag.equalsIgnoreCase("linkText")) {
webelement = driver.findElement(By.linkText(objectLocator));
//highlightElement(driver, webelement);
} else if (locatorTag.equalsIgnoreCase("class")) {
webelement = driver
.findElement(By.className(objectLocator));
//highlightElement(driver, webelement);
} else if (locatorTag.equalsIgnoreCase("css")) {
webelement = driver.findElement(By
.cssSelector(objectLocator));
//highlightElement(driver, webelement);
} else {
String error = "Please Check the Given Locator Syntax :"
+ locator;
error = error.replaceAll("'", """);
return null;
}
} catch (Exception e) {
ExtentTestManager.getTest().log(LogStatus.FAIL, "Failure Reason:- "+e.getMessage());
Assert.assertTrue(false);
String error = "Please Check the Given Locator Syntax :"
+ locator;
error = error.replaceAll("'", """);
e.printStackTrace();
return null;
}
}
return webelement;
}
//Click Method
public void click(By elementLocation) {
waitVisibility(elementLocation);
driver.findElement(elementLocation).click();
}
//Write Text
public void writeText(By elementLocation, String text) {
waitVisibility(elementLocation);
driver.findElement(elementLocation).sendKeys(text);
}
//Read Text
public String readText(By elementLocation) {
waitVisibility(elementLocation);
return driver.findElement(elementLocation).getText();
}
//Wait
public void waitVisibility(By by){
wait.until(ExpectedConditions.visibilityOfElementLocated(by));
}
public WebElement findByClassName(String ClassName) {
WebElement element = driver.findElement(By.className(ClassName));
return element;
}
/**
* Find WebElement By CssSelector.
*
* @param CssSelector
* @return Return Web Element.
*/
public WebElement findByCssSelector(String CssSelector) {
WebElement element = driver.findElement(By.cssSelector(CssSelector));
return element;
}
/**
* @param locator
* desc Whether the checkbox is checked or not
*/
public static boolean isCheckboxChecked(String locator) {
WebElement element = findElement(locator);
if (element.isSelected())
return true;
else
return false;
}
/**
* * @param locator
* @return list of webelement found
*/
public static List<WebElement> findElements(String locator) {
if (locator != null) {
String[] arrLocator = locator.split("==");
String locatorTag = arrLocator[0].trim();
String objectLocator = arrLocator[1].trim();
if (locatorTag.equalsIgnoreCase("id")) {
webelements = driver.findElements(By.id(objectLocator));
} else if (locatorTag.equalsIgnoreCase("name")) {
webelements = driver.findElements(By.name(objectLocator));
} else if (locatorTag.equalsIgnoreCase("xpath")) {
webelements = driver.findElements(By.xpath(objectLocator));
} else if (locatorTag.equalsIgnoreCase("linkText")) {
webelements = driver.findElements(By.linkText(objectLocator));
} else if (locatorTag.equalsIgnoreCase("class")) {
webelements = driver.findElements(By.className(objectLocator));
} else {
System.out.println("Please Check the Locator Syntax Given :"
+ locator);
return null;
}
}
return webelements;
}
/**
* @param locator
* desc Check a Checkbox having a particular value as its attribute
*/
public static void CheckCheckBox(String Locator, String Value)
{
List<WebElement> oCheckBox = findElements(Locator);
// This will tell you the number of checkboxes are present
int iSize = oCheckBox.size();
// Start the loop from first checkbox to last checkbox
for(int i=0; i < iSize ; i++ ){
// Store the checkbox name to the string variable, using 'Value' attribute
String sValue = oCheckBox.get(i).getAttribute("value");
// Select the checkbox it the value of the checkbox is same what you are looking for
if (sValue.equalsIgnoreCase(Value))
{
oCheckBox.get(i).click();
// This will take the execution out of for loop
break;
}
}
}
/**
* ram ID
* <p>
* Find Web Element By ID.
*
* @paturn Return Web Element.
*/
public WebElement findById(String ID) {
WebElement element = driver.findElement(By.id(ID));
return element;
}
/**
* @throws AWTException
*/
public static void PressShiftTab() throws AWTException {
Robot robot = new Robot();
robot.delay(3000);
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_SHIFT);
}
/**
* @throws AWTException
*/
public static void PressTab() throws AWTException {
Robot robot = new Robot();
robot.delay(3000);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
}
/**
* @param locator of the Web Element
* @param attributeName
* @return attributeValue
*/
public static String getAttribute(String locator, String attributeName) {
String attributeValue = null;
try {
WebElement element = findElement(locator);
if (element != null)
attributeValue = element.getAttribute(attributeName);
element = null;
} catch (Exception e) {
e.printStackTrace();
}
return attributeValue;
}
/**
* @param locator of the Element to be cleared
*/
public static void clearElement(String locator) {
try {
WebElement element = findElement(locator);
element.clear();
element = null;
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param locator
* @param value
*/
public static void enterText(String locator, String value) {
try {
WebElement element = findElement(locator);
element.sendKeys(value);
element = null;
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param locator of Element to be clicked
* @return
*/
public static void click(String locator) {
try {
WebElement element = findElement(locator);
if (element != null)
element.click();
else
System.out.println("Element Is NULL");
element = null;
/*Assert.assertTrue(false);*/
} catch (Exception e) {
System.out.println(" Error occured whlie click on the element "
+ locator + " *** " + e.getMessage());
ExtentTestManager.getTest().log(LogStatus.FAIL, "Failure Reason:- "+e.getMessage());
Assert.assertTrue(false);
}
}
/**
* @param locator
* @return Text/value of the Element
*/
public static String getElementText(String locator) {
WebElement element;
String text = null;
try {
element = findElement(locator);
if (element != null)
text = element.getText();
} catch (Exception e) {
e.printStackTrace();
ExtentTestManager.getTest().log(LogStatus.FAIL, "Failure Reason:- "+e.getMessage());
Assert.assertTrue(false);
}
element = null;
return text;
}
/**
* @param propertyType
* @param propertyValue
*/
public static void mouseHover(String locator) {
WebElement mouseOverElement = findElement(locator);
Actions builder = new Actions(driver); // Configure the Action
Action mouseOver =builder.moveToElement(mouseOverElement).build(); // Get the action
mouseOver.perform(); // Execute the Action
}
/**
* Find Web Element By findByLinkText.
*
* @param linkText
* @return Return Web Element.
*/
public WebElement findByLinkText(String linkText) {
WebElement element = driver.findElement(By.linkText(linkText));
return element;
}
/**
* Find Web Element By Name.
*
* @param Name
* @return Return Web Element.
*/
public WebElement findByName(String Name) {
WebElement element = driver.findElement(By.name(Name));
return element;
}
/**
* Find Web Element By Partial_Link_Text.
*
* @param PartialLinkText
* @return Return Web Element.
*/
public WebElement findByPartialLinkText(String PartialLinkText) {
WebElement element = driver.findElement(By.partialLinkText(PartialLinkText));
return element;
}
/**
* Find Web Element By Tag_Name.
*
* @param TagName
* @return Return Web Element.
*/
public WebElement findByTagName(String TagName) {
WebElement element = driver.findElement(By.tagName(TagName));
return element;
}
/**
* Find Web Element By findByXpath.
*
* @param XpathExpression
* @return Return Web Element.
*/
public WebElement findByXpath(String XpathExpression) {
WebElement element = driver.findElement(By.xpath(XpathExpression));
return element;
}
}
步骤定义:
package stepdefinition;
import java.lang.reflect.Method;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.ITestContext;
import io.cucumber.java.en.Given;
import main.CucumberRunner;
import pages.CuraLoginPage;
public class LoginStep extends CucumberRunner {
CuraLoginPage curaloginpage;
@Given("^User logged in with "(.*)" and "(.*)"$")
public void user_login(String logicalName,String url) throws Throwable {
System.out.println(logicalName);
System.out.println(url);
Method method; ITestContext iTestContext;
try {
curaloginpage.LogintoCura(logicalName, url); **>>> NULL POINTER EXCEPTION**
}
catch(Exception e){
e.printStackTrace();
}
}
}
StackTrace:
java.lang.NullPointerException
at stepdefinition.LoginStep.user_login(LoginStep.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at io.cucumber.java.Invoker.invoke(Invoker.java:27)
at io.cucumber.java.JavaStepDefinition.execute(JavaStepDefinition.java:27)
at io.cucumber.core.runner.PickleStepDefinitionMatch.runStep(PickleStepDefinitionMatch.java:63)
at io.cucumber.core.runner.TestStep.executeStep(TestStep.java:64)
at io.cucumber.core.runner.TestStep.run(TestStep.java:49)
at io.cucumber.core.runner.PickleStepTestStep.run(PickleStepTestStep.java:46)
at io.cucumber.core.runner.TestCase.run(TestCase.java:51)
at io.cucumber.core.runner.Runner.runPickle(Runner.java:67)
at io.cucumber.testng.TestNGCucumberRunner.runScenario(TestNGCucumberRunner.java:124)
at io.cucumber.testng.AbstractTestNGCucumberTests.runScenario(AbstractTestNGCucumberTests.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:134)
at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:597)
at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:173)
at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:816)
at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:146)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.testng.TestRunner.privateRun(TestRunner.java:766)
at org.testng.TestRunner.run(TestRunner.java:587)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:384)
at org.testng.SuiteRunner.access$000(SuiteRunner.java:28)
at org.testng.SuiteRunner$SuiteWorker.run(SuiteRunner.java:425)
at org.testng.internal.thread.ThreadUtil.lambda$execute$0(ThreadUtil.java:68)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
[当我初次尝试用TestNG做黄瓜时,请提供帮助。我没有在步骤定义中使用驱动程序。我真的不确定是什么导致NullPointerException发生
答案
似乎您尚未在步骤定义中创建CuraLoginPage的实例。如果您使用的是TestNG页面对象模型,则需要添加如下内容。
CuraLoginPage curaloginpage;
public LoginStep()
{
curaloginpage = new CuraLoginPage(driver);
}
[如果可能,然后也共享CuraLoginPage的代码。
以上是关于黄瓜分步定义处的空指针异常的主要内容,如果未能解决你的问题,请参考以下文章
方法 oncreateview 中片段中 listview.setadapter() 的空指针异常