Null pointer Exception in Testng annotations - java

can any one tell me why im getting NullPointerException for the 2nd method, if I only write one method and execute it not getting any exception, below is the code, your support is really appreciated-:
public class Test1234 {
static WebDriver driver;
#Test
public void testsetup() throws Exception
{
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver_win32\\chromedriver.exe");
driver=new ChromeDriver();
driver.get("https://www.gmail.co.in");
//driver.manage().window().maximize();
File src=new File("./read1.properties");
FileInputStream sd=new FileInputStream(src);
Thread.sleep(1000);
Properties pr=new Properties();
pr.load(sd);
String usern=pr.getProperty("username");
System.out.println(usern);
driver.findElement(By.id("identifierId")).sendKeys(usern);
}
#Test
public void drr()
{
driver.getTitle();
String s=driver.getTitle();
Assert.assertEquals(s, s, "pass");
System.out.println(s);
}
}

In TestNG you can use #BeforeTest annotation on a method to initialize objects as driver for all tests:
#BeforeTest
public void init() {
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver_win32\\chromedriver.exe");
driver=new ChromeDriver();
}
#BeforeTest: The annotated method will be run before any test method belonging to the classes inside the tag is run.

Related

Selenium with TestNG Script is not working?

Selenium with TestNG Script is not working? Script is not working in testng framework but in a modular framework, it is working fine ?? Here is the code snapshot.
//Script To Register Inside The Application
public class AppTest{
WebDriver driver;
#BeforeMethod
public void setup() {
System.setProperty("webdriver.chrome.driver","F:\\ResourceFiles\\chromedriver_win32\\chromedriver_win32\\chromedriver.exe");
WebDriver driver =new ChromeDriver();
driver.get("http://newtours.demoaut.com/mercurywelcome.php");
driver.manage().window().maximize();
// driver.manage().timeouts().implicitlyWait(8000, TimeUnit.SECONDS);
}
#Test
public void registerApp(){
//driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[2]/td/table/tbody/tr/td[2]/a")).click();
driver.findElement(By.linkText("REGISTER")).click();
driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[2]/td[2]/input")).sendKeys("kartikey");
driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[3]/td[2]/input")).sendKeys("gautam");
driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[4]/td[2]/input")).sendKeys("7248006980");
driver.findElement(By.xpath("//*[#id=\"userName\"]")).sendKeys("kartikeygautam#gmail.com");
driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[7]/td[2]/input")).sendKeys("22 Dayal Bagh Colony");
driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[9]/td[2]/input")).sendKeys("Agra");
driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[10]/td[2]/input")).sendKeys("UttarPradesh");
driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[11]/td[2]/input")).sendKeys("282005");
Select fruits = new Select(driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[12]/td[2]/select")));
fruits.selectByVisibleText("INDIA ");
driver.findElement(By.xpath("//*[#id=\"email\"]")).sendKeys("kartikeygautam#gmail.com");
driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[15]/td[2]/input")).sendKeys("Mummyp#p#123");
driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[16]/td[2]/input")).sendKeys("Mummyp#p#123");
driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[16]/td[2]/input")).click();
driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[18]/td/input")).click();
}
#Test
public void loginApp() {
driver.get("http://newtours.demoaut.com/mercurywelcome.php");
driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[2]/td[3]/form/table/tbody/tr[4]/td/table/tbody/tr[2]/td[2]/input")).sendKeys("kartikeygautam");
driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[2]/td[3]/form/table/tbody/tr[4]/td/table/tbody/tr[3]/td[2]/input")).sendKeys("Mummyp#p#123");
driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[2]/td[3]/form/table/tbody/tr[4]/td/table/tbody/tr[4]/td[2]/div/input")).click();
}
#AfterMethod
public void tearDown() {
driver.quit();
}
}
Your #BeforeMethod is not setting a value to the class instance of driver, it's generating a new driver object that only exists in the context of the #BeforeMethod. You need to tweak your #BeforeMethod to be:
#BeforeMethod
public void setup() {
System.setProperty("webdriver.chrome.driver","F:\\ResourceFiles\\chromedriver_win32\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://newtours.demoaut.com/mercurywelcome.php");
driver.manage().window().maximize();
}

JUnit Annotations not being run through

I have a JUnit Framework with the following annotations #before, #test, #After.
However when I run through my tests the #After Annotation is never initialised and therefore the browser doesn't close.
I've run my tests using JUnit and they all pass but the tear down step never works.
I decided to try see if any of the annotations worked, so I removed the #before and #test and the test still run and passed which suggests to me that they are not being used at all.
This is my Selenium set up:
public SeleniumSetup() {
}
#Before
public void prepareBrowserForSelenium() throws Exception {
// setup();
if(DriverSingleton.getDriver() == null)
{
setup();
}
else
{
driver = DriverSingleton.getDriver();
}
}
public void setup() throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\antho\\Automation\\WebAutomation\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.ultimateqa.com");
driver.manage().window().maximize();
DuringTest();
}
#Test
public void DuringTest() throws Exception{
System.out.println("test has started");
assertEquals(true, driver.getPageSource().contains("Learn Critical Automation and Dev Skills"));
System.out.println("Learn Critical Automation and Dev Skills copy has been verified");
driver.findElement(By.linkText("Automation Exercises")).click();
assertEquals(true, driver.getPageSource().contains("Automation Practice"));
System.out.println("Automation Practice copy has been verified");
driver.findElement(By.linkText("Big page with many elements")).click();
}
#After
public static void tearDown() throws Exception {
driver.close();
}
This is my DriverSingleton;
private static WebDriver driver;
public DriverSingleton () {
}
public static WebDriver getDriver() {
return driver;
}
public static void setDriver (WebDriver driver) {
DriverSingleton.driver = driver;
}
}
After my tests have run I expect the browser to close down.
I have added DuringTest(); to my #Before class, which I suspect is the only reason the #Test class is getting called, without that this the #Test doesn't work.
First you shall not invoke #Test inside your setup method by calling DuringTest(). JUnit framework would take care of Test Method by looking #Test annotations. So you do not need to call it explicitly.
Make both #Before & #After method as non static.
If you were running a test with this code you should have seen an exception with the following message being thrown by JUnit:
Method tearDown() should not be static
Method annotated with JUnit test annotations should always be non-static and located inside dedicated classes used exclusively for running tests. Use the following code as a base to further build your test class:
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class SeleniumTest {
#Before
public void prepareBrowserForSelenium() throws Exception {
System.out.println("Running method annotated with #Before");
}
#Test
public void DuringTest() throws Exception {
System.out.println("Running main test method");
}
#After
public static void tearDown() throws Exception {
System.out.println("Running method annotated with #After");
}
}
Console output:
Running method annotated with #Before
Running main test method
Running method annotated with #After
As you see everything work just fine. I would suggest reading more about JUnit testing in general and here is a good place to start:
https://github.com/junit-team/junit4/wiki/Getting-started

How to write Selenium Java Application code in IDE through main() and TestNG

I m facing the below issue
searched in Google couldn't find the clear answer how to resolve this.
Error :
org.apache.bcel.verifier.exc.AssertionViolatedException.main(AssertionViolatedException.java:102)
Code
import org.openqa.selenium.chrome.ChromeDriver;
public class Newtours
{
public static ChromeDriver driver;
public void chrome()
{
System.setProperty("webdriver.chrome.driver","C:\\Users\\imper\\Downloads\\chro‌​medriver_win32\\chro‌​medriver.exe"); // objects and variables instantiation
driver = new ChromeDriver();
driver.get("newtours.demoaut.com/");
}
}
The error is stemming out of org.apache.bcel.verifier
You have to take care of a certain things as follows :
Instead of using the ChromeDriver implementation use the WebDriver interface.
chrome is a reserved keyword. Use some other user defined name for the method e.g. my_function() {}
Simply defining public void chrome() won't execute your Test. You have to convert public void chrome() in to either of the following :
Convert into main() function as follows:
public class Newtours
{
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://newtours.demoaut.com/");
}
}
Integrate TestNG and add #Test annotations as follows :
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class Newtours
{
#Test
public void my_function()
{
System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://newtours.demoaut.com/");
}
}
System.setProperty("webdriver.chrome.driver", "chromedriver");
driver = new ChromeDriver();
driver.get("http://newtours.demoaut.com/");
Try this code it's working fine.
I checked this and it's running fine.
You need to give http or https for your url.

NullPointerException in Selenium WebDriver Instance When Using in TestNG

I have created a Selenium test suite using TestNG for my website.
The name of my project is Test My Website. In order to execute my Selenium test script and create a test report, I execute the TestNG.xml file directly from the command prompt. For different modules of my website, I have created different Java classes for different modules and have kept them in one package. The source code of my files is given as follows:
TestNG.xml
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Test My Website">
<test name="My Website Test">
<packages>
<package name="testmywebsite" />
</packages>
</test>
</suite>
TestLogin.java
public class TestLogin {
public static WebDriver driver;
#BeforeTest
public void setup() {
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
#Test
void loginTest() {
//Code to perform the login test
}
#AfterClass
public void setupWorkHistory() {
TestModule1.driver = driver;
}
}
TestModule1.java
public class TestModule1 {
public static WebDriver driver;
#Test
void module1Test() {
//Code to perform the module 1 test
driver.getTitle();
}
#AfterClass
public void setupModule2() {
TestModule2.driver = driver;
}
}
TestModule2.java
public class TestModule2 {
public static WebDriver driver;
#Test
void module2Test() {
//Code to perform the module 2 test
driver.getTitle();
}
#AfterTest
public void tearDown() {
driver.close();
driver.quit();
}
}
Note that in the first two Java classes I have added the setup<Next Class's name>() method to pass my driver instance.
The problem here is that the driver instance gets successfully passed from TestLogin.java to TestModule1.java. However it throws a NullPointerException in the module2Test() method and hence it shows a failed TestNG report for module2Test() despite creating the setupModule2() method in TestModule1.java and adding the #AfterClass annotation to it.
Can anyone tell me why exactly is this happening here? Replies at the earliest will be highly appreciated. Thank you.
Okay I found a solution to the problem myself.
For that I edited the source code of my TestNG.xml file and my Java class files. They are given as follows:
TestNG.xml
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Test RockON">
<test name="Rockon Test" allow-return-values="true">
<classes>
<class name="testmywebsite.TestLogin" />
<class name="testmywebsite.TestModule1" />
<class name="testmywebsite.TestModule2" />
</classes>
</test>
</suite>
TestLogin.java
public class TestLogin {
public static WebDriver driver;
#BeforeTest
public void setup() {
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
#Test
void loginTest() {
//Code to perform the login test
}
public static WebDriver getDriver() {
return driver;
}
}
TestModule1.java
public class TestModule1 {
public static WebDriver driver;
#BeforeClass
public void setup() {
driver = TestLogin.getDriver();
}
#Test
void module1Test() {
//Code to perform the module 1 test
}
public static WebDriver getDriver() {
return driver;
}
}
Module2.java
public class TestModule2 {
public static WebDriver driver;
#BeforeClass
public void setup() {
driver = TestModule1.getDriver();
}
#Test
void module2Test() {
//Code to perform the module 2 test
}
public static WebDriver getDriver() {
return driver;
}
}
What I did is called the classes individually from my XML file and added the allow-return-values="true" attribute to my tests, which allows the classes to allow return types. In my Java classes I instantiated my WebDriver instance in every class in a #BeforeClass method. Hence I was able to prevent my WebDriver instance from throwing a NullPointerException.

Use same web driver throughout selenium suite

I have a the following selenium test suite inheriting from the same base class, how to I have the tests use the same web driver instance when i run the entire test suite?. I also want to run each tests in isolation aswell. I believe this will cut down the time it takes to run the suite considerably.
This test is run from maven that in turn runs each test class.
#RunWith(Suite.class)
#SuiteClasses({
AdminPortalTestSuite.class,
DevPortalTestSuite.class,
CommonTestSuite.class
})
public class SeleniumTestSuite {
}
Baseclass all tests inherit from
#BeforeClass
public static void setUp() throws Exception {
if (null == baseUrl || !baseUrl.startsWith("https://")) {
baseUrl = "https://localhost:8443";
}
if (null == browser || browser.startsWith("${")) {
browser = "firefox";
}
//retrieve properties including locale.
retrieveProperties();
Thread.sleep(4000);
setUpDriver();
}
#After
public void tearDownAfterTest() {
openUrl(LIST_PARTNERS);
adminPortalLogout();
openUrl(DASHBOARD);
developerPortalLogout();
driver.manage().deleteAllCookies();
}
#AfterClass
public static void tearDown() throws Exception {
BaseFunctionalTestCase.driver.quit();
}
test example
public class APApplicationFunctionalTestCase extends BaseFunctionalTestCase {
/**
* Test validation when creating a new application.
*/
#Test
public void testApplicationValidation() {
Assume.assumeTrue(preHtml5);
final String partnerName = randomize("partner");
//create partner
createPartnerThroughAP(partnerName);
adminPortalLogin();
openUrl(ADD_APPLICATION + partnerName);
waitForId("applicationView.applicationName");
findById("submit-button").click();
waitForId("submit-button");
//check validation
assertTrue("Failed to validate application name",
isTextPresent(resolveAPMessage("partner", "application.messages",
"NotEmpty.applicationEditView.applicationView.applicationName")));
assertTrue("Failed to validate application username",
isTextPresent(resolveAPMessage("partner", "application.messages",
"NotEmpty.applicationEditView.applicationView.applicationUserName")));
assertTrue("Failed to validate application password",
isTextPresent(resolveAPMessage("partner", "application.messages",
"Password.applicationEditView.applicationView.applicationPassword")));
assertTrue("Failed to validate application password confirmation",
isTextPresent(resolveAPMessage("partner", "application.messages",
"Length.applicationEditView.applicationPasswordConfirmation")));
}
This is how I did it. In SeleniumTestSuite, I added a static WebDriver and instantiate it in a setUp() method annotated with #BeforeClass. Then, in the Base class that all of my selenium tests inherit from, I added a getDriver() method, that will try to get the static driver from SeleniumTestSuite. If that driver is null, then a new one gets instantiated and returned. Thus, when the selenium test classes are running via the suite, they will use the driver from SeleniumTestSuite, and when they are running individually, they will use their own driver.
SeleniumTestSuite:
#RunWith(Suite.class)
#SuiteClasses({
AbcSeleniumTest.class,
XyzSeleniumTest.class
})
public class SeleniumTestSuite {
private static WebDriver driver;
#BeforeClass
public static void setUp() {
driver = new FirefoxDriver();
}
//driver getter/setter
}
BaseSeleniumTest:
public abstract class BaseSeleniumTest {
public WebDriver getDriver() {
WebDriver driver = SeleniumTestSuite.getDriver();
if(driver != null) {
return driver;
}
return new FirefoxDriver();
}
}
AbcSeleniumTest:
public class AbcSeleniumTest extends BaseSeleniumTest {
#Test
public void testAbc() {
WebDriver driver = getDriver();
// test stuff
}
}
I'm not great with JUnit... looks like you're trying the solution suggested here:
Before and After Suite execution hook in jUnit 4.x
which would suggest you should move your #BeforeClass into your SeleniumTestSuite class.

Categories