Getting Null Pointer Exception while executing listener class from testNG xml

2,669 views
Skip to first unread message

Viji Lakshmi

unread,
Jun 27, 2013, 6:03:40 AM6/27/13
to testng...@googlegroups.com

I am trying to execute listener class.While executing as TestNG test,test is successful.But when executing from testNG xml,its throwing null pointer exception.Please help me to resolve this issue.

Listener class:

@Listeners({SearchPageToDemonstrateFail.class})

public class SearchPageToDemonstrateFail extends TestListenerAdapter{
    public String baseurl="http://www.sears.com/shc/s/CountryChooserView?storeId=10153&catalogId=12605";
      public static WebDriver driver;
      public int Count = 0;

    @BeforeTest 
      public void searchPage_openBrowser() {

          driver = new FirefoxDriver();
          driver.manage().deleteAllCookies();
          driver.get(baseurl);
      }
@Test
public void searchPage_validations_Failure() throws InterruptedException{
          driver.findElement(By.id("intselect")).sendKeys("India");
        driver.findElement(By.xpath(".//*[@id='countryChooser']/a/img")).click();
        driver.findElement(By.xpath(".//*[@id='keyword']")).sendKeys("shirts");
        driver.findElement(By.xpath(".//*[@id='goBtn']")).click();

            ...

        driver.findElement(By.xpath(".//*[@id='sortOptions']"));
        System.out.println("Recommend dropdown");



        try {
              WebElement e = driver.findElement(By.xpath(".//*[@id='content']/div[3]/div[6]/div[2]/div)[2]"));
              Assert.assertTrue(e.isDisplayed());
              String strng = e.getText();
              System.out.println(strng);
              Assert.assertEquals("Relevance", strng);
              System.out.println("Relevance value selected in sortby dropdown");
            } 
            catch(NoSuchElementException n) {
               System.out.println("Relevance value not selected in sortby dropdown");
            } catch(AssertionError a) {
               System.out.println("Asser Error:Relevance value not selected in sortby dropdown");
            }

        driver.findElement(By.xpath(".//*[@id='resultsView']/span"));
        System.out.println("View Text");
            ...
        driver.findElement(By.xpath(".//*[@id='resultsNxtBtn']"));
        System.out.println("Next page link");


        //General Validations
        driver.findElement(By.xpath(".//*[@id='changeCountry']/span"));     
        System.out.println("Change Country Link");
            ...
        driver.findElement(By.xpath(".//*[@id='footerNav']/li[7]/a")).click();
        System.out.println("Moresears sites");
        System.out.println("---------------------------------------");
        System.out.println("Search Page test case-Success");
        System.out.println("---------------------------------------");

}

public void searchPage_screenshot() 
{
      try{
     Date date=new Date();
        Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");        
        File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");  
        FileUtils.copyFile(scrnsht, new File(NewFileNamePath));
        System.out.println(NewFileNamePath);
        Reporter.log("<a href=\"" + NewFileNamePath + "\">Screenshot</a>"); 

      }
      catch (IOException e) {

          e.printStackTrace();

          }

          }


@AfterTest
public void searchPage_closeBrowser() {
     driver.quit(); 
}

@Override
    public void onTestFailure(ITestResult tr) {

     Reporter.log("Fail");


            String workingDirectory = System.getProperty("user.dir");
            String fileName = workingDirectory + File.separator + "screenShots" + File.separator +  tr.getMethod().getMethodName() + "().png";//filename

            File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

            try {

                FileUtils.copyFile(scrFile, new File(fileName ));

            } catch (IOException e) {
                // TODO Auto-generated catch block
                                e.printStackTrace();

                Reporter.log("error generating screenshot:" +e, true);
            }


    }

@Override
      public void onTestSkipped(ITestResult result) {
      // will be called after test will be skipped
    //searchPage_screenshot();
        Reporter.log("Skip");
      }
      @Override
      public void onTestSuccess(ITestResult result) {
      // will be called after test will pass
          //searchPage_screenshot();
     Reporter.log("Pass");
      }

}

TestNG xml:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="Smoke Suite For International" verbose="1" preserve-order="true" parallel="false">

       <listeners>
        <listener class-name="maintestcases.SearchPageToDemonstrateFail" />
    </listeners>    

  <test name="Group 1 - Browse Test Cases" >
    <classes>    
      <class name="maintestcases.Validations_HomePage" />
      <class name="maintestcases.ChoseCountry_CountryChoserLayer" />
      <class name="maintestcases.ChoseCountry_ChangeCountryLink" />
       <class name="maintestcases.Validations_VerticalPage" />
       <class name="maintestcases.Validations_CategoryPage" />         
       <class name="maintestcases.Validations_SubCategoryPage" />
       <class name="maintestcases.Validations_ProductPage" /> 
  </classes>
  </test>  
    <test name="Group 2 - Browse Test Cases" >
    <classes>      
       <class name="maintestcases.Validations_SearchPage" />  

       <class name="maintestcases.Validations_ComparePage" />
    </classes>
    </test>

      <test name="Group 3- Email Test Case" >
     <classes>   
      <class name="maintestcases.SendMailSSL" />          
          </classes>
   </test>
  </suite>

I am getting null pointer exception and getting error in below mentioned line of OnTestFailure method

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);  

Stacktrace:

java.lang.NullPointerException
    at maintestcases.SearchPageToDemonstrateFail.onTestFailure(SearchPageToDemonstrateFail.java:224)
    at org.testng.internal.Invoker.runTestListeners(Invoker.java:1895)
    at org.testng.internal.Invoker.runTestListeners(Invoker.java:1879)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1292)
    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:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    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)

Krishnan Mahadevan

unread,
Jun 27, 2013, 8:44:38 PM6/27/13
to testng...@googlegroups.com
Viji,
You are getting a NPE [ NullPointerException ] because you are initialising your driver object in @BeforeTest but TestNG never invoked it. TestNG would never invoke annotated methods in a class if you told TestNG to use a given class as a TestNG listener ( which is what you are doing here ). 

To get past your issue you would need to add the same listener class as part of your <tests> tag as well. Only then the @BeforeTest method would get invoked and your WebDriver object get initialized. 


On a side note, I dont think its a good practice to mingle your listener and test specific actions into the same class. You should try and keep your Test specific code separate from your listener code. 
--
You received this message because you are subscribed to the Google Groups "testng-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to testng-users...@googlegroups.com.
To post to this group, send email to testng...@googlegroups.com.
Visit this group at http://groups.google.com/group/testng-users.
For more options, visit https://groups.google.com/groups/opt_out.
 
 


--
Thanks & Regards
Krishnan Mahadevan

"All the desirable things in life are either illegal, expensive, fattening or in love with someone else!"
My Scribblings @ http://wakened-cognition.blogspot.com/
Reply all
Reply to author
Forward
0 new messages