Null pointer exception for Extent Report - selenium-webdriver

It wouldbe silly question but would be great help it you can help me out.
I tried implementing extent report for multple test cases, but report are not getting generated .
Code:
public class SampleTc1
{
static WebDriver driver;
static ExtentReports report;
static ExtentTest logger;
static void testcase1()
{
System.setProperty("webdriver.chrome.driver","chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.google.co.in");
logger.log(LogStatus.PASS, "This step is passed");
driver.close();
}
}
public class SampleTc2
{
static WebDriver driver;
static ExtentReports report;
static ExtentTest logger;
static void testcase2()
{
System.setProperty("webdriver.chrome.driver","chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.google.co.in");
logger.log(LogStatus.PASS, "This step is passed");
driver.close();
}
}
Main Class:
public class Maindriver {
static WebDriver driver;
static ExtentReports report;
static ExtentTest logger;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
report=new ExtentReports("./Report/ExtentReport/ExecutionResult.html", true);
logger=report.startTest("TC1", "Testc Case1");
SampleTc1.testcase1();
report.endTest(logger);
logger=report.startTest("TC2", "Testc Case2");
SampleTc2.testcase2();
report.endTest(logger);
report.flush();
}
}
After running no reports are getting generated and it is showing null ponter exception:
Exception in thread "main" java.lang.NullPointerException
at SmokeTest.SampleTc1.testcase1(SampleTc1.java:24)
at SmokeTest.Maindriver.main(Maindriver.java:22)
Above exception I am getting.
Thanks in advance.

If you are using testng for running selenium suite, you can implement extent reports as a listener.
Like,
public class ExtentReporterNG implements IReporter
{
public ExtentReports extent;
private void buildTestNodes(IResultMap testMap, LogStatus status)
{
ExtentTest test;
if (testMap.size() > 0)
{
for (ITestResult result : testMap.getAllResults())
{
//test = extent.startTest(result.getInstance().getClass().getSimpleName(),result.getMethod().getMethodName());
test = extent.startTest(result.getMethod().getMethodName().toUpperCase(),result.getInstance().getClass().getSimpleName().toUpperCase());
test.assignCategory(result.getInstance().getClass().getSimpleName().toUpperCase());
test.setStartedTime(getTime(result.getStartMillis()));
for (String group : result.getMethod().getGroups())
test.assignCategory(group);
String message = "Test " + status.toString().toLowerCase() + "ed";
if (result.getThrowable() != null)
message = result.getThrowable().getMessage();
test.setEndedTime(getTime(result.getEndMillis()));
test.log(status, message);
extent.endTest(test);
}
}
}
private Date getTime(long millis)
{
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millis);
return calendar.getTime();
}
#Override
public void generateReport(List<XmlSuite> xmlsuite, List<ISuite> suites,String file)
{
final String filePath=GlobalSettings.getProperty(GlobalSettings.EXTENTFILE);
extent = new ExtentReports(filePath, true,DisplayOrder.NEWEST_FIRST,NetworkMode.OFFLINE );
extent.loadConfig(new File("./config/extentConfig.xml"));
for (ISuite suite : suites)
{
Map<String, ISuiteResult> result = suite.getResults();
for (ISuiteResult r : result.values())
{
ITestContext context = r.getTestContext();
buildTestNodes(context.getPassedTests(), LogStatus.PASS);
buildTestNodes(context.getFailedTests(), LogStatus.FAIL);
buildTestNodes(context.getSkippedTests(), LogStatus.SKIP);
buildTestNodes(context.getFailedConfigurations(),LogStatus.FAIL);
buildTestNodes(context.getSkippedConfigurations(),LogStatus.SKIP);
}
}
extent.flush();
extent.close();
}}

It is not well organized, hard to say what/where is the problem ...
You can check here a selenium webdriver testng tutorial I used it when I started and it is a good starting point!

You have to change your ExtentReports as static in the base class. I got this idea from Mukesh Otwani, Selenium automation trainer for Learn-Automation.

I created separate class for extent report, hence avoided NULL pointer exception

Related

How to fix this NullPointerException with selenium and java?

I am trying to run my Automation script, I am launching URL but I am getting java.lang.NullPointerException
package lib.Page;
public class LoginPage {
public static final String URL = null;
public static final String TITLE = null;
public static final String EMAIL = null;
public static final String PASSWORD = null;
WebDriver driver;
WebDriverWait wait;
public LoginPage(WebDriver driver, WebDriverWait wait) {
this.driver = driver;
this.wait = wait;
}
public LoginPage lauchUrl(String url){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.get(LoginPageData.URL);
return this;
Check your stack trace for the exact row where you are getting this error. My guess would be this:
driver.get(LoginPageData.URL);
as I don't see you initializing LoginPageData anywhere.

Cucumber #Before hook runs twice #After once

to all.
Curently writing a little BDD Test automation framework, using Java11+Junit5+Cucumber+Selenium, build tool: Graddle. Created a little test for validating Google title. When starting test, using Test task in Graddle or running CucumberRunner class, in both cases getting the same result: two times #Before method is executed, once #After method is executed and one browser windows is staying open. After added one more test, the same situation, only 4 browsers are opened, 2 of them are closing. Can anyone help with this situation?
Link to repository
After some watching of logs saw, that, seems, #Before is not executed twice, but Driver class is initialized twice, but why it happens no idea for now...
My code for now:
CucumberRunner.java:
#RunWith(Cucumber.class )
#CucumberOptions(
features = "src\\test\\java\\features",
glue = {"steps", "utils"},
tags = "#smoke")
public class CucumberRunner {
}
Driver.java:
public class Driver {
private WebDriver driver;
public Driver(){
driverInitialization();
}
private void driverInitialization(){
System.setProperty("webdriver.chrome.driver", "D:\\Soft\\selenium-drivers\\chromedriver.exe");
System.out.println("Starting driver.");
var browserName = "chrome";
switch (browserName.toLowerCase()){
case "chrome":
System.out.println("Starting chrome");
driver = new ChromeDriver();
System.out.println("Before break.");
break;
case "firefox":
driver = new FirefoxDriver();
break;
default:
throw new NotFoundException("Browser not found: " + browserName);
}
}
public WebDriver getDriver(){
return driver;
}
public WebDriverWait getWebDriverWait(){
return new WebDriverWait(driver, 120);
}
public void terminateDriver(){
System.out.println("Terminating driver.");
if (driver != null) {
driver.close();
driver.quit();
}
}
}
Hooks.java:
public class Hooks {
private Driver driver;
#Before
public void setup(){
System.out.println("In the Setup method.");
driver = new Driver();
}
#After
public void tearDown(){
System.out.println("In the TearDown method.");
driver.terminateDriver();
}
}
I think your Hook Class should be like this As You Are Using selenium-picocontainer DI.
public class Hooks {
private Driver driver;
public Hooks(Driver driver) {
this.driver = driver;
}
#Before
public void setup(){
System.out.println("In the Setup method.");
}
#After
public void tearDown(){
System.out.println("In the TearDown method.");
driver.terminateDriver();
}
}

Page Objects erro (java.lang.NullPointerException)

I did a basic project to training about Page Objects using selenium WebDriver with java and Junit. So, I make a page object class and Junit class too. I Make a call of method and pass the parameters to method but, the eclipse show a message that say: java.lang.NullPointerException
public class LogarBkoMaisPage {
static WebDriver driver;
By campoNome = By.id("matricula_I");
By campoSenha = By.id("senha_I");
By btnLogin = By.id("bt_entrar");
public LogarBkoMaisPage(WebDriver driver) {
this.driver = driver;
}
public void logar(String usuario, String senha) {
driver.findElement(campoNome).sendKeys(usuario);
driver.findElement(campoSenha).sendKeys(senha);
driver.findElement(btnLogin).click();
}
}
public class LogarBkoMaisTest {
static WebDriver driver;
#Before
public void setUp() throws Exception {
SelecionarNavegador nav = new SelecionarNavegador();
nav.iniciarNavegador("ie","http://10.5.9.45/BkoMais_Selenium/");
}
#Test
public void logarAplicacao() {
try {
LogarBkoMaisPage login = new LogarBkoMaisPage(driver);
login.logar("844502","Bcc201707");
}catch(Exception e) {
System.out.println("Mensagem de erro: " +e);
}
}
#After
public void tearDown() throws Exception {
}
}
public class SelecionarNavegador {
static WebDriver driver;
public static WebDriver iniciarNavegador(String nomeNavegador, String url) {
if(nomeNavegador.equalsIgnoreCase("firefox")) {
System.setProperty("webdriver.gecko.driver", "E:\\workspace_BCC_QA_BKOMAIS\\"
+ "FireFoxGeckodriver64\\geckodriver.exe");
driver = new FirefoxDriver();
}
else if(nomeNavegador.equalsIgnoreCase("chrome")){
System.setProperty("webdriver.chrome.driver", "E:\\workspace_BCC_QA_BKOMAIS"
+ "\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
}else if(nomeNavegador.equalsIgnoreCase("IE")) {
System.setProperty("webdriver.ie.driver", "E:\\workspace_BCC_QA_BKOMAIS"
+ "\\IE Plugin\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
driver.manage().window().maximize();
driver.get(url);
return driver;
}
}
Exception:
You are getting a null pointer exception because iniciarNavegador method inside SelecionarNavegador class is the one which initializes the driver and it returns the driver which has to be assigned to a vairable. You need to do this in your setUp()method
#Before
public void setUp() throws Exception {
SelecionarNavegador nav = new SelecionarNavegador();
driver=nav.iniciarNavegador("ie","http://10.5.9.45/BkoMais_Selenium/");
}

Selenium POM java.lang.NullPointerException

I am getting "java.lang.NullPointerException" when I am trying to execute my test case based on POM.
The class BrowserFactory lets me choose a browser, the class Flipkart_Login based on POM stores all the element of that particular page and has a method for Valid_Login()
and finally Test_Flipkart_Login class - calls the Valid_Login() method for executon but when I try to execute this class, I get java.lang.NullPointerException.
Kindly advise!
FAILED: Flipkart_Login_Test
java.lang.NullPointerException
at DataProviders.ConfigDataProvider.getURL(ConfigDataProvider.java:31)
at TestCases.Test_Flipkart_Login.Flipkart_Login_Test(Test_Flipkart_Login.java:19)
public class ConfigDataProvider
{
static Properties pro;
public ConfigDataProvider()
{
File src = new File("C:\\Data\\Bimlesh\\Flipkart_HybridFramework\\Flipkart.Hybrid.FrameworkComplete\\Configuration\\Config.Properties");
try
{
FileInputStream fis = new FileInputStream(src);
pro = new Properties();
pro.load(fis);
} catch (Exception e)
{
System.out.println("The Config exception is :"+e.getMessage());
}
}
public static String getURL()
{
String URL = pro.getProperty("URL");
return URL;
}
public static String ChromePath()
{
String Chrome = pro.getProperty("Chromepath");
return Chrome;
}
public static String IEPath()
{
String IE = pro.getProperty("IEpath");
return IE;
}
}
public class BrowserFactory
{
static WebDriver driver;
public static WebDriver getBrowser(String BrowserName)
{
if(BrowserName.equalsIgnoreCase("Firefox"))
{
driver = new FirefoxDriver();
}
else if(BrowserName.equalsIgnoreCase("Chrome"))
{
System.setProperty("webdriver.chrome.driver", ConfigDataProvider.ChromePath());
driver = new ChromeDriver();
}
else if(BrowserName.equalsIgnoreCase("IE"))
{
System.setProperty("webdriver.ie.driver", ConfigDataProvider.IEPath());
driver = new InternetExplorerDriver();
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
return driver;
}
public void ShutDown(WebDriver driver)
{
driver.quit();
}
}
public class Flipkart_Login
{
WebDriver driver;
public Flipkart_Login(WebDriver driver)
{
this.driver=driver;
}
#FindBy(xpath="//a[text()='Log In']") WebElement Login_Click;
#FindBy(xpath="//input[#class='_2zrpKA' and #type='text']") WebElement Enter_Email;
#FindBy(xpath="//input[#class='_2zrpKA _3v41xv' and #type='password']") WebElement Enter_Pass;
#FindBy(xpath="//button[#type='submit' and #class='_3zLR9i _1LctnI _36SmAs']") WebElement Login_Button;
public void Valid_Login()
{
Login_Click.click();
Enter_Email.sendKeys("xxx#gmail.com");
Enter_Pass.sendKeys("xxx");
Login_Button.click();
}
}
public class Test_Flipkart_Login
{
WebDriver driver;
#Test
public void Flipkart_Login_Test()
{
driver = BrowserFactory.getBrowser("Firefox");
driver.get(ConfigDataProvider.getURL());
Flipkart_Login page1 = PageFactory.initElements(driver, Flipkart_Login.class);
page1.Valid_Login();
}
}
You have initialized Properties pro in the constructor of the COnfigDataProider but you are using a static call to getURL method from your test class. Thus pro will be null and not initialized. Remove static call and use the constructor or make pro to static and initialize in static block.

How to declare the driver (chrome/ie) globally which is used in both main and sub methods in cross Browser testing

While automating cross browser test, I used the driver in both main and sub method. It is showing syntax error in the line "System.setProperty("webdriver.chrome.driver","D:\chromedriver_win32"
Thanks
import org.openqa.selenium.chrome.ChromeDriver;
public class MyClass {
System.setProperty("webdriver.chrome.driver","D:\\chromedriver_win32\\chromedriver.exe");
static WebDriver driver = new ChromeDriver();
public static void main(String[] args) throws IO Exception {
driver.findElement(By.id("aaa")).clear();
-do-
String B = new MyClass().gettext("eeee");
}
driver.quit();
}
public String getIframe(String id) {
driver.findElement(By.id("ddd")).clear();
-do-
return A;
}
}
I resolved it by modifying the code as below:
import org.openqa.selenium.chrome.ChromeDriver;
public class MyClass {
static Webdriver driver;
public static void main(String[] args) throws IO Exception {
System.setProperty("webdriver.chrome.driver","D:\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.findElement(By.id("aaa")).clear();
-do-
String B = new MyClass().gettext("eeee");
}
driver.quit();
}
public String getIframe(String id) {
driver.findElement(By.id("ddd")).clear();
-do-
return A;
}
}
So Simple!!!

Resources