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();
}
Related
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.
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\\chromedriver_win32\\chromedriver.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.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm trying to use #beforeSuite and #AfterSuite to run my test in one browser instance. however it run the first the first test class but fail with null pointer exception when it the second class.
Here is my code below:
LaunchBrowser.java class
public class LaunchBrower {
protected WebDriver driver;
public WebDriver getDriver() {
return driver;
}
#Parameters({ "browserType", "appURL" })
#BeforeSuite
public void setUp(#Optional String browsertype, #Optional String appURL) {
System.out.println("Launching google chrome with new profile..");
driver = getBrowserType(browsertype);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.navigate().to(appURL);
}
private WebDriver getBrowserType(String browserType) {
if (driver == null ) {
if (browserType.equalsIgnoreCase("chrome")) {
return new ChromeDriver();
}
else if (browserType.equalsIgnoreCase("InternetExplorer")) {
return new InternetExplorerDriver();
}
}
return driver;
}
#AfterSuite
public void tearDown() {
if (driver != null)
driver.quit();
}
}
LoginPageTest class
public class LoginPageTest extends LaunchBrower {
protected WebDriver driver;
private LoginPage loginpage;
private MyProfile profilepage;
Logger log = Logger.getLogger("Results:");
#BeforeClass(alwaysRun = true)
public void setUp() {
loginpage = PageFactory.initElements(getDriver(), LoginPage.class);
//loginpage = new LoginPage(driver);
//driver=getDriver();
}
#Test(groups = "LoginPage")
public void verifyLogin() throws InterruptedException {
//LoginPage login = new LoginPage(driver);
System.out.println("Sign In functionality details...");
//System.out.println("Sign In functionality details seee...");
Thread.sleep(10000);
//login.enterUserName("11111111");
Assert.assertEquals("11111111",loginpage.enterUserName("11111111"));
log.debug("Correct Username Pass");
//System.out.println("Correct username...");
Assert.assertEquals("fe9245db",loginpage.enterPassword("fe9245db"));
log.debug("Correct Password Pass");
loginpage.clickOnLogin();
log.debug("Login Pass");
}
}
MyProfileTest java class
public class MyProfileTest extends LaunchBrower {
protected WebDriver driver;
private MyProfile profilepage;
#BeforeClass(alwaysRun = true)
public void setUp() {
profilepage = PageFactory.initElements(getDriver(), MyProfile.class);
//driver=getDriver();
}
#Test(groups = "Myprofile")
public void verifyMyprofile() throws InterruptedException {
System.out.println("My profile test...");
//MyProfile profile = new MyProfile(driver);
profilepage.ClickToggleLink();
profilepage.ClickMyProfile();
}
}
The problem lies in your test code. #BeforeSuite is designed in TestNG to be invoked only once per <suite>. You are combining that logic along with inheritance and then relying on the #BeforeSuite method to initialize your WebDriver. So it will do it for the first class in your <suite> by from the second class onwards TestNG is not going to be invoking the #BeforeSuite and thus your second class onwards you start seeing the NullPointerException.
You should instead consider relying on a ISuiteListener implementation as a listener and then wire it into your test execution.
Your tests would now start relying on a webdriver that is created in this manner and then work with it.
Please ensure that you are using TestNG 6.12 or higher (which at this point doesn't exist).
Here's a full fledged example that shows all of this in action.
The base class of my test classes look like below
package com.rationaleemotions.stackoverflow.qn46323434;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.Listeners;
#Listeners(BrowserSpawner.class)
public class MyBaseClass {
protected void launchPage(String url) {
RemoteWebDriver driver = BrowserSpawner.getDriver();
driver.get(url);
System.err.println("Page Title :" + driver.getTitle());
}
}
The test classes that I am using in this example look like below
package com.rationaleemotions.stackoverflow.qn46323434;
import org.testng.annotations.Test;
public class MyFirstTestCase extends MyBaseClass {
#Test
public void testGooglePage() {
launchPage("http://www.google.com");
}
#Test
public void testFaceBookPage() {
launchPage("http://www.facebook.com");
}
}
package com.rationaleemotions.stackoverflow.qn46323434;
import org.testng.annotations.Test;
public class MySecondTestCase extends MyBaseClass {
#Test
public void testHerokkuPage() {
launchPage("https://the-internet.herokuapp.com/");
}
#Test
public void testStackOverFlowPage() {
launchPage("http://stackoverflow.com/");
}
}
The ISuiteListener implementation looks like below
package com.rationaleemotions.stackoverflow.qn46323434;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.ISuite;
import org.testng.ISuiteListener;
import org.testng.ITestResult;
import org.testng.Reporter;
public class BrowserSpawner implements ISuiteListener {
private static final String DRIVER = "driver";
#Override
public void onStart(ISuite suite) {
RemoteWebDriver driver;
String browserType = suite.getParameter("browserType");
switch (browserType) {
case "chrome":
driver = new ChromeDriver();
break;
default:
driver = new FirefoxDriver();
}
suite.setAttribute(DRIVER, driver);
}
#Override
public void onFinish(ISuite suite) {
Object driver = suite.getAttribute(DRIVER);
if (driver == null) {
return;
}
if (!(driver instanceof RemoteWebDriver)) {
throw new IllegalStateException("Corrupted WebDriver.");
}
((RemoteWebDriver) driver).quit();
suite.setAttribute(DRIVER, null);
}
public static RemoteWebDriver getDriver() {
ITestResult result = Reporter.getCurrentTestResult();
if (result == null) {
throw new UnsupportedOperationException("Please invoke only from within an #Test method");
}
Object driver = result.getTestContext().getSuite().getAttribute(DRIVER);
if (driver == null) {
throw new IllegalStateException("Unable to find a valid webdriver instance");
}
if (! (driver instanceof RemoteWebDriver)) {
throw new IllegalStateException("Corrupted WebDriver.");
}
return (RemoteWebDriver) driver;
}
}
The suite xml file that I am using looks like below
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="46323434_Suite" parallel="false" verbose="2">
<parameter name="browserType" value="chrome"/>
<test name="46323434_test1">
<classes>
<class name="com.rationaleemotions.stackoverflow.qn46323434.MyFirstTestCase"/>
</classes>
</test>
<test name="46323434_test2">
<classes>
<class name="com.rationaleemotions.stackoverflow.qn46323434.MySecondTestCase"/>
</classes>
</test>
</suite>
When you run this the output would look like below
...
... TestNG 6.12 by Cédric Beust (cedric#beust.com)
...
Starting ChromeDriver 2.32.498537 (cb2f855cbc7b82e20387eaf9a43f6b99b6105061) on port 45973
Only local connections are allowed.
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
Sep 20, 2017 10:36:41 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Page Title :Facebook – log in or sign up
Page Title :Google
PASSED: testFaceBookPage
PASSED: testGooglePage
===============================================
46323434_test1
Tests run: 2, Failures: 0, Skips: 0
===============================================
Page Title :The Internet
Page Title :Stack Overflow - Where Developers Learn, Share, & Build Careers
PASSED: testHerokkuPage
PASSED: testStackOverFlowPage
===============================================
46323434_test2
Tests run: 2, Failures: 0, Skips: 0
===============================================
===============================================
46323434_Suite
Total tests run: 4, Failures: 0, Skips: 0
===============================================
The most important things to remember here are :
Your tests are no longer going to be starting and cleaning up the browser. This is now going to be done by your ISuiteListener implementation.
Due to the model that is being used (i.e., relying on one browser instance per <suite>) you will never be able to run your tests in parallel. All of your tests should strictly run in sequential manner.
You need to ensure that none of your #Test methods either crash the browser (or) cause the browser instance to be cleaned up (this is applicable when you are dealing with a Grid setup wherein you probably endup leaving the browser idle for sometime causing the node to cleanup the browser from the server side). If you cause any of this, then your tests are going to fail with unexpected results.
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.
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.