AppiumDriver gives null pointer exception - java

In my appium + testng app, what I have put is:
package com.tribehr.ios.ios_test;
import java.net.URL;
import io.appium.java_client.AppiumDriver;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.*;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;
import org.testng.Assert;
public class NewTest {
private AppiumDriver driver;
#Before
public void setUp() throws Exception {
// set up appium
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
capabilities.setCapability("platformVersion", "7.1");
capabilities.setCapability("platformName", "iOS");
capabilities.setCapability("deviceName", "iPhone Simulator");
capabilities.setCapability("app", "/path to .app");
driver = new AppiumDriver(new URL("http://0.0.0.0:4723/wd/hub"), capabilities);
}
#After
public void tearDown() throws Exception {
driver.quit();
}
#Test
public void Test1() throws Exception {
driver.findElement(By.xpath("//UIAApplication[1]/UIAWindow[1]/UIATextField[1]/UIATextField[1]"));
}
}
The following stack trace is given:
[TestNG] Running:
/private/var/folders/hh/r5f5h1lx23g6drvycy03g29w0000gs/T/testng-eclipse--1877089062/testng-customsuite.xml
FAILED: Test1
java.lang.NullPointerException
at com.tribehr.ios.ios_test.NewTest.Test1(NewTest.java:39)
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:483)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
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)
===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
===============================================
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter#7b1d7fff: 23 ms
[TestNG] Time taken by org.testng.reporters.jq.Main#7b3300e5: 28 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 2 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2#2ff5659e: 4 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter#43556938: 4 ms
[TestNG] Time taken by org.testng.reporters.JUnitReportReporter#57fa26b7: 2 ms
It seems like the Appium server is not instantiated successfully with the capability, but this is almost a copy-and-paste of examples online - and I cannot figure out what goes wrong..

Surround "driver" with an if statement, to understand whether it == null.
if(driver!=null){
System.out.println("driver does not == null");
driver.findElement(By.xpath("YourXpath"));
} else {
System.out.println("driver == null")
}
Here are my capabilities Working with appium 1.2*
public WebDriver appiumCapabilities() {
File appDir = new File(System.getProperty("user.dir"), "/app/");
File app = new File(appDir, "test.app");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.BROWSER_NAME, "iOS");
capabilities.setCapability(CapabilityType.PLATFORM, "Mac");
capabilities.setCapability("platformName", "iOS");
capabilities.setCapability("deviceName", "iPod");
capabilities.setCapability("platformVersion", "7.1");
capabilities.setCapability("device", "iphone");
capabilities.setCapability("udid", "cd827d3778cfdee2fc7210f8f44184821a083c06");
capabilities.setCapability("app", app);
try {
driver = new RemoteWebDriver(new URL("http://0.0.0.0:4723/wd/hub"), capabilities);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return driver;
}

Related

Why am I getting org.openqa.selenium.StaleElementReferenceException exception in my code given below?

Hi Everyone I was trying to make a Selenium Script to verify the validations on Username and Password Text Box by fetching the data from Excel file (.xlt format) but whenever i am running my code it is getting the following error after successful loop run . The code is as follows :
package com.selenium.com.selenium.practise;
import org.testng.annotations.Test;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.testng.annotations.BeforeMethod;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
public class MultipleCasesUsingExcel {
public static WebDriver driver = null;
#Test
public void Test() throws BiffException, IOException, InterruptedException {
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// Clicking on My Account Link
driver.findElement(By.xpath("//*[#id='top']/body/div/div/div[3]/div/div[4]/ul/li[1]/a")).click();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
WebElement emailTextBox = driver.findElement(By.xpath("//input[#id='email']"));
WebElement pwdTextBox = driver.findElement(By.xpath("//input[#id='pass']"));
WebElement loginBtn = driver.findElement(By.xpath("//button[#id='send2']"));
Workbook book = Workbook.getWorkbook(new File("C:\\Users\\Umang Bhatia\\Documents\\data.xlt"));
Sheet sheet = book.getSheet(0);
for (int i = 0; i < sheet.getRows(); i++) {
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
}
for (int j = 0; j < sheet.getColumns() - 1; j++) {
emailTextBox.sendKeys(sheet.getCell(j, i).getContents());
pwdTextBox.sendKeys(sheet.getCell(j + 1, i).getContents());
loginBtn.click();
emailTextBox.clear();
pwdTextBox.clear();
}
Thread.sleep(3000);
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#BeforeMethod
public void beforeMethod() {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Umang Bhatia\\Documents\\Selenium Drivers\\chrome driver\\chromedriver.exe");
driver = new ChromeDriver();
driver.navigate().to("http://live.guru99.com/index.php/");
}
#AfterMethod
public void afterMethod() {
driver.quit();
}
}
And I am getting the following error after first successful loop run :
[RemoteTestNG] detected TestNG version 6.13.1
Starting ChromeDriver 2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f) on port 36887
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.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
FAILED: Test
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
(Session info: chrome=63.0.3239.132)
(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.10586 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 31 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:55:52'
System info: host: 'DESKTOP-59DNS54', ip: '192.168.2.5', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_121'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f), userDataDir=C:\Users\UMANGB~1\AppData\Local\Temp\scoped_dir13984_1984}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=63.0.3239.132, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, setWindowRect=true, unexpectedAlertBehaviour=}]
Session ID: eb78d1ac176166bdaa86da5dc12e09c0
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:647)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:326)
at org.openqa.selenium.remote.RemoteWebElement.clear(RemoteWebElement.java:139)
at com.selenium.com.selenium.practise.MultipleCasesUsingExcel.Test(MultipleCasesUsingExcel.java:55)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:571)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:707)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:979)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
at org.testng.SuiteRunner.run(SuiteRunner.java:364)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1187)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1116)
at org.testng.TestNG.runSuites(TestNG.java:1028)
at org.testng.TestNG.run(TestNG.java:996)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
===============================================
Could any one Explain why I am getting this error and how it can be fixed
That's because you change page in your test, thus your element references break. Have a look at WebDriverExtensions. This framework provides method on opening your links in new windows without invalidating references of WebElements, and enables dynamic lookup of your elements.
Alternatively, if you don't want to use this framework, you could re-search for your elements in your loop like this:
//...
for (int j = 0; j < sheet.getColumns() - 1; j++) {
// add these lines
emailTextBox = driver.findElement(By.xpath("//input[#id='email']"));
pwdTextBox = driver.findElement(By.xpath("//input[#id='pass']"));
loginBtn = driver.findElement(By.xpath("//button[#id='send2']"));
// clear inputs before login. After you click loginBtn, the page
// changes, and references of WebElements are invalidated,
// thus your emailTextBox.clear(); methods threw anexception
emailTextBox.clear();
pwdTextBox.clear();
emailTextBox.sendKeys(sheet.getCell(j, i).getContents());
pwdTextBox.sendKeys(sheet.getCell(j + 1, i).getContents());
loginBtn.click();
}

First test fails on IntelliJ IDEA + Appium

I'm a new one to automation. I've set up an environment for test automation, but I'm unable to run my first test, errors occurs on each run. Have no idea what it is, please help me
Here is my code:
import io.appium.java_client.android.AndroidDriver;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;
public class FirstTest {
AndroidDriver androidDriver;
#Before
public void setUp() throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("devicename", "Testdevice");
androidDriver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
}
#Test
public void logInCheck() throws Exception {
androidDriver.findElement(By.id("com.example.mariia.testing:id/button")).click();
}
#After
public void tearDown() throws Exception {
androidDriver.quit();
}
}
Here are the errors that i'm receiving:
java.lang.NullPointerException
at FirstTest.logInCheck(FirstTest.java:34)
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:85)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
at org.testng.TestRunner.privateRun(TestRunner.java:774)
at org.testng.TestRunner.run(TestRunner.java:624)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
at org.testng.SuiteRunner.run(SuiteRunner.java:261)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
at org.testng.TestNG.run(TestNG.java:1048)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:74)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:124)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
You haven't set capabilities platformName, platformVersion,app and deviceName. You're testing Android app, so You need to provide additionally capabilites appActivity and appPackage.
DesiredCapabilities caps = new DesiredCapabilities();
caps.SetCapability("app-package", "com.myapp.test");
caps.SetCapability("browserName", "");
caps.SetCapability("device", "Android");
caps.SetCapability("app-activity", "com.myapp.SplashActivity");
caps.SetCapability("version", "4.1.2");
caps.SetCapability("device ID", "uniquedeviceid");
caps.SetCapability("app", "apk-path");
To narrow down your issue, please provide your testng.xml file.

java.lang.ClassNotFoundException is comming when running appium script

I am very new to appium:
i wanted to run a code where in my device i open chrome and open a google.com:
#BeforeMethod
public void setUp() throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("browserName", "Browser");
capabilities.setCapability("device", "Android");
capabilities.setCapability("deviceName", "TA9330416L");
capabilities.setCapability("platformVersion", "5.1");
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("appPackage", "com.android.chrome");
driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"),capabilities);
}
#AfterMethod
public void tearDown() throws Exception {
driver.quit();
}
#Test
public void launchWebsite()throws InterruptedException {
driver.get("http://www.google.com");
}
but getting the following error:
?* FAILED CONFIGURATION: #BeforeMethod setUp
java.lang.NoClassDefFoundError: com/google/common/base/Function
at WhatsApp.setUp(WhatsApp.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:86)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:514)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:215)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:589)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:820)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1128)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:782)
at org.testng.TestRunner.run(TestRunner.java:632)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:366)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:319)
at org.testng.SuiteRunner.run(SuiteRunner.java:268)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1246)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1171)
at org.testng.TestNG.run(TestNG.java:1066)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:113)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:206)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:177)
Caused by: java.lang.ClassNotFoundException: com.google.common.base.Function
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 27 more
SKIPPED CONFIGURATION: #AfterMethod tearDown
SKIPPED: launchWebsite*/
You need to add this dependendcy jar https://code.google.com/p/guava-libraries/
Have to created any test class? Error says no class definition found. You have to create on test class first and define functions in the class. I have not tried on the android browser but I have automated android hybrid and native apps using appium.
package test;
import java.net.URL;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import io.appium.java_client.android.AndroidDriver;
public class TestBrowser {
public AndroidDriver driver;
public TestBrowser() {
//To do
}
#BeforeMethod
public void setUp() throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("appium-version", "1.0");
capabilities.setCapability("browserName", "Browser");
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("deviceName", "TA9330416L");
capabilities.setCapability("platformVersion", "5.1");
capabilities.setCapability("appPackage", "com.android.chrome");
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
}
#AfterMethod
public void tearDown() throws Exception {
if(driver!=null)
driver.quit();
}
#Test
public void launchWebsite()throws InterruptedException {
driver.get("http://www.google.com");
}
}

Selenium Webdriver UnreachableBrowserException

I am getting this error:
org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died.
Build info: version: '2.45.0', revision: '32a636c', time: '2015-03-05 22:01:35'
System info: host: 'HOME', ip: '10.1.11.121', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_31'
Driver info: driver.version: RemoteWebDriver
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:593)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:352)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByName(RemoteWebDriver.java:425)
at org.openqa.selenium.By$ByName.findElement(By.java:299)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:344)
at com.tests.TestClass2.test2(TestClass2.java:14)
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:483)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
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)
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to 127.0.0.1:7055 [/127.0.0.1] failed: Connection refused: connect
at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:140)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:318)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:363)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:219)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:72)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57)
at org.openqa.selenium.remote.internal.ApacheHttpClient.fallBackExecute(ApacheHttpClient.java:126)
at org.openqa.selenium.remote.internal.ApacheHttpClient.execute(ApacheHttpClient.java:72)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:133)
at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.execute(NewProfileExtensionConnection.java:165)
at org.openqa.selenium.firefox.FirefoxDriver$LazyCommandExecutor.execute(FirefoxDriver.java:362)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:572)
... 29 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at org.apache.http.conn.socket.PlainConnectionSocketFactory.connectSocket(PlainConnectionSocketFactory.java:72)
at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:123)
... 44 more
My Environment:
OS: Windows 7
JDK: javac 1.8.0_31
FireFox: ESR 31.4.0
Eclipse: 4.4.2.20150219-0708
Selenium: selenium-2.45.0
Testng: 6.8.6.20141201_2240
I am using a Testing suite file to run 2 classes (TestClass1 & TestClass 2). It throws above error when invoking browser for 2nd class. Here is my complete Project
Base Class:
public class BaseClass {
public static WebDriver driver = new FirefoxDriver();
public static boolean implicitwait(long time) {
try {
driver.manage().timeouts().implicitlyWait(time, TimeUnit.SECONDS);
} catch (Exception e) {
return false;
}
return true;
}
#BeforeClass
public static boolean LaunchBrowser() throws InterruptedException {
implicitwait(50000);
try {
System.setProperty("webdriver.firefox.bin",
"C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
driver.navigate().to("https:google.com");
driver.manage().window().maximize();
implicitwait(5000);
} catch (Exception e) {
return false;
}
System.out.println("Launching Browser & Navigating To Page");
return true;
}
#AfterClass
public void CloseBrowser() {
driver.close();
System.out.println("Closing Browser");
}
}
Test Class:
#Test
public class TestClass extends BaseClass {
public void test1(){
System.out.println("TEST 1");
driver.findElement(By.name("q")).sendKeys("ABC");
driver.findElement(By.name("btnG")).click();
}
}
Test Class2
#Test
public class TestClass2 extends BaseClass {
public void test2(){
System.out.println("TEST 2");
driver.findElement(By.name("q")).sendKeys("DEF");
driver.findElement(By.name("btnG")).click();
}
}
I would super appreciate if someone can let me know what I am doing wrong
My Testng.xml:
<test name="Run Test Class In Firefox">
<classes>
<class name="com.tests.TestClass" />
<class name="com.tests.TestClass2" />
</classes>
</test>
Use #BeforeSuite and #AfterSuite instead of #BeforeClass and #AfterClass
#AfterClass
public void CloseBrowser() {
driver.close();
System.out.println("Closing Browser");
}
Basically closing the current browser instance after the first class and thus, the driver instance is not valid to run the tests for next class. You can test this by commenting out the #AfterClass
Reference
EDIT
Video
Gist

Powemockito constructor testing problems

Hej I have some problems with TestNG and powerMockito 1.5.x I tried with 1.5.5 and 1.5.6. The problem is when I try to verify a constructor that is not empty.
I've check quite some examples around about extending from PowerMockTestCase and so on but they do not seem to work for me.
package com.cdev.common;
public class TestSubject {
String data;
String context;
public TestSubject()
{
this.data = "Mock!!";
this.context = "PowerMockito";
}
public TestSubject(String data)
{
this.data = data;
this.context = "PowerMockito";
}
public TestSubject(String data,String context)
{
this.data = data;
this.context = context;
}
public String getData()
{
throw new UnsupportedOperationException();
}
public String getContext()
{
throw new UnsupportedOperationException();
}
public boolean isNew()
{
throw new UnsupportedOperationException();
}
}
This is the testNG test:
package com.cdev.common.test;
import com.cdev.common.*;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.testng.Assert;
import org.testng.annotations.Test;
#PrepareForTest({TestSubject.class})
public class TestSubjectTest{
#Test
public void TestSubject() throws Exception
{
System.out.println("======== Test ==================");
TestSubject mockTestSubject = PowerMockito.mock(TestSubject.class);
PowerMockito.whenNew(TestSubject.class).withArguments("A", "B").thenReturn(mockTestSubject);
PowerMockito.when(mockTestSubject.getData()).thenReturn("A");
PowerMockito.when(mockTestSubject.getContext()).thenReturn("B");
PowerMockito.when(mockTestSubject.isNew()).thenReturn(true);
PowerMockito.verifyNew(TestSubject.class).withArguments("A", "B");
TestSubject lala = new TestSubject("A","B");
System.out.println(lala.getData());
System.out.println(lala.isNew());
Assert.assertTrue(lala.getData().equals("A"), "Not equal");
}
}
This gives me this output:
[TestNG] Running:
/tmp/testng-eclipse--2099806353/testng-customsuite.xml
======== Test ==================
FAILED: TestSubject
java.lang.AssertionError: Wanted but not invoked com.cdev.common.TestSubject(
"A",
"B"
);
Actually, there were zero interactions with this mock.
at org.powermock.api.mockito.internal.invocation.InvocationControlAssertionError.throwAssertionErrorForNewSubstitutionFailure(InvocationControlAssertionError.java:93)
at org.powermock.api.mockito.internal.verification.DefaultConstructorArgumentsVerfication.invokeSubstitute(DefaultConstructorArgumentsVerfication.java:51)
at org.powermock.api.mockito.internal.verification.DefaultConstructorArgumentsVerfication.withArguments(DefaultConstructorArgumentsVerfication.java:44)
at com.cdev.common.test.TestSubjectTest.TestSubject(TestSubjectTest.java:32)
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:483)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
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)
===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
===============================================
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter#6d9c638: 18 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2#2401f4c3: 6 ms
[TestNG] Time taken by org.testng.reporters.JUnitReportReporter#5d22bbb7: 3 ms
[TestNG] Time taken by org.testng.reporters.jq.Main#3d012ddd: 31 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 2 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter#1175e2db: 5 ms
You need to move the verifyNew call to after the invocation has been made:
TestSubject lala = new TestSubject("A","B");
PowerMockito.verifyNew(TestSubject.class).withArguments("A", "B");
Following your instructions:
#Test
public void TestSubject() throws Exception
{
System.out.println("======== Test ==================");
TestSubject mockTestSubject = PowerMockito.mock(TestSubject.class);
PowerMockito.whenNew(TestSubject.class).withArguments("A", "B").thenReturn(mockTestSubject);
PowerMockito.when(mockTestSubject.getData()).thenReturn("A");
PowerMockito.when(mockTestSubject.getContext()).thenReturn("B");
PowerMockito.when(mockTestSubject.isNew()).thenReturn(true);
**TestSubject lala = new TestSubject("A","B");
PowerMockito.verifyNew(TestSubject.class).withArguments("A", "B");**
System.out.println(lala.getData());
System.out.println(lala.isNew());
Assert.assertTrue(lala.getData().equals("A"), "Not equal");
}
The output:
[TestNG] Running:
/tmp/testng-eclipse--349458877/testng-customsuite.xml
======== Test ==================
FAILED: TestSubject
java.lang.AssertionError: Wanted but not invoked com.cdev.common.TestSubject(
"A",
"B"
);
Actually, there were zero interactions with this mock.
at org.powermock.api.mockito.internal.invocation.InvocationControlAssertionError.throwAssertionErrorForNewSubstitutionFailure(InvocationControlAssertionError.java:93)
at org.powermock.api.mockito.internal.verification.DefaultConstructorArgumentsVerfication.invokeSubstitute(DefaultConstructorArgumentsVerfication.java:51)
at org.powermock.api.mockito.internal.verification.DefaultConstructorArgumentsVerfication.withArguments(DefaultConstructorArgumentsVerfication.java:44)
at com.cdev.common.test.TestSubjectTest.TestSubject(TestSubjectTest.java:28)
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:483)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
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)
===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
===============================================
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter#6d9c638: 36 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2#2401f4c3: 8 ms
[TestNG] Time taken by org.testng.reporters.JUnitReportReporter#5d22bbb7: 13 ms
[TestNG] Time taken by org.testng.reporters.jq.Main#3d012ddd: 45 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 4 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter#1175e2db: 5 ms

Categories