Appium driver null pointer exception - java

I am new to Appium and just getting started, I have been following an example and using a basic Contacts apk on Android tablet to start against. The code I have is pretty much copied from the example I am following but when I try to run the test I get a null pointer exception. I did some debugging and find that the driver = null is why I am getting this exception. I looked around and found some code that I thought might help but it hasn't.
The code I have is
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;
import java.net.MalformedURLException;
import java.net.URL;
public class addContact {
AppiumDriver driver;
#Before
public void setUp () throws Exception {
new DesiredCapabilities();
DesiredCapabilities capabilities = DesiredCapabilities.android();
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME,"AndroidTestDevice");
try
{
driver = new AndroidDriver(new URL("http://0.0.0.0:4723/wd/hub"), capabilities);
driver.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS);
}
catch (MalformedURLException e)
{
System.out.println("URL init error");
}
}
#After
public void tearDown () throws Exception {
driver.quit();
}
#Test
public void addNewContact (){
System.out.println (driver);
WebElement addContactButton = driver.findElementById("com.example.android.contactmanager:id/addContactButton");
addContactButton.click();
}
}`
The exception I get is :
java.lang.NullPointerException
at addContact.addNewContact(addContact.java:49)
and the line this occurs in is :
WebElement addContactButton = driver.findElementById("com.example.android.contactmanager:id/addContactButton");

The reason it showing as null pointer because you are using "testng" annotation for "Tests" and "junit" annotation for "Before and after". Change import org.testng.annotations.Test; to import org.junit.Test; and run it as junit test.
This should work, just tested it on my side.

Related

Not found constructor AndroidDriver with Appium in eclipse

Code with errors:
package TestCase;
import java.net.MalformedURLException;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.gargoylesoftware.htmlunit.javascript.host.URL;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
import io.appium.java_client.remote.MobilePlatform;
public class TestWebBrowser {
//AppiumDriver driver = new IOSDriver();
public static AndroidDriver driver;
public static void main(String[] args) throws MalformedURLException {
DesiredCapabilities capabilities = new DesiredCapabilities();
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
}
}
The message error is:
The constructor URL(string) is undefined
The constructor AndroidDriver(URL, DesiredCapabilities) is undefined
AndroidDriver is a raw type
I have tried with different versions of java-client and still the problem persists
You need to use an existen constructor like this:
https://appium.github.io/java-client/io/appium/java_client/android/AndroidDriver.html
You need use java.net.URL and not com.gargoylesoftware.htmlunit.javascript.host.URL
#Lorena, hi.
1. Firstly, could You please double check the imports ? Sharing code snippet below with correct ones
package tests.web;
import java.net.MalformedURLException;
import java.net.URL;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileBrowserType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
public class AndroidWebTest {
private static final String ACCESS_KEY = System.getenv(“SEETEST_IO_ACCESS_KEY”);
private static final String CLOUD_URL = “https://cloud.seetest.io:443/wd/hub”;
private static final String TITLE = “Testing Website on Android Chrome with Java”;
private AndroidDriver driver = null;
#Before
public void setUp() throws MalformedURLException {
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability(“testName”, TITLE);
dc.setCapability(“accessKey”, ACCESS_KEY);
dc.setBrowserName(MobileBrowserType.CHROME);
driver = new AndroidDriver(new URL(CLOUD_URL), dc);
}
#Test
public void testAppiumOnChrome() {
driver.get(“https://amazon.com”);
System.out.println(driver.getTitle());
if (driver.getCapabilities().getCapability(“device.category”).equals(“TABLET”)) {
driver.findElement(By.xpath(“//*[#name=’field-keywords’]”)).sendKeys(“iPhone”);
driver.findElement(By.xpath(“//*[#text=’Go’]”)).click();
} else {
driver.findElement(By.xpath(“//*[#name=’k’]”)).sendKeys(“iPhone”);
driver.findElement(By.xpath(“//*[#value=’Go’]”)).click();
}
}
#After
public void tearDown() {
if (driver != null) {
driver.quit();
}
}
}
Please see the Comparing and combining web and mobile test automation drivers article for more details.
If You project is maven-based, could You please also double check the dependencies?
For example, please see latest appium updates here
Appropriate maven repo to check for (latest) java client:
https://mvnrepository.com/artifact/io.appium/java-client

java.lang.module.FindException: while using selenium

I am fairly new to selenium, and I was trying to use some of the scripts being used in tutorials for my practice. I downloaded all the required .JAR files (Chrome drivers, Selenium Java and Stand Alone server) and added it to the path in Eclipse.
Below is the Code which I am trying to run to access a Weblink and then trying to verify if a user is able to log in successfully or not.
package learnautomation;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class practice {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "Mypath\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.gcrit.com/build3/admin/");
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("password")).sendKeys("admin#123");
driver.findElement(By.id("tdb1")).click();
String url = driver.getCurrentUrl();
if (url.equals("http://www.gcrit.com/build3/admin/index.php")){
System.out.println("Successful");
}
else {
System.out.println("Unsuccessful");
}
driver.close();
}
}
While doing this I am getting this error:
"Error occurred during initialization of boot layer
java.lang.module.FindException: Module seleniumnew not found"
Also, import org.openqa.selenium.chrome.ChromeDriver; it says this is not accessible as well when I just hover over it.
try this, just edit paths and package name.
package navi;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Avi {
public static WebDriver driver;
WebDriverWait wait5s = new WebDriverWait(driver,5);
#BeforeClass
public static void setUpClass() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\pburgr\\Desktop\\chromedriver\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=C:\\Users\\pburgr\\AppData\\Local\\Google\\Chrome\\User Data");
driver = new ChromeDriver(options);
driver.manage().window().maximize();}
#Before
public void setUp() {}
#After
public void tearDown() {}
#AfterClass
public static void tearDownClass() {driver.close();driver.quit();}
#Test
public void avi() throws InterruptedException {
driver.get("http://www.gcrit.com/build3/admin/");
wait5s.until(ExpectedConditions.elementToBeClickable(By.name("username"))).sendKeys("admin");
driver.findElement(By.name("password")).sendKeys("admin#123");
driver.findElement(By.id("tdb1")).click();
// wait to resolve the click before checking url
Thread.sleep(1000);
String url = driver.getCurrentUrl();
if (url.equals("http://www.gcrit.com/build3/admin/index.php")){
System.out.println("Successful");
}
else {
System.out.println("Unsuccessful");
}
}
}

Appium-JAVA Error: unable to load class 'org.eclipse.ui.internal.ide.application.addons.ModelCleanupAddon' from bundle '731'

stacktrace screenshot I am trying to run different tests that I have written, through Appium on an Android device, but I am getting the following errors:
unable to load class 'org.eclipse.ui.internal.ide.application.addons.ModelCleanupAddon' from bundle '731'
or
unable to load class 'org.eclipse.ui.internal.ide.application.addons.ModelCleanupAddon' from bundle '561'
My code is:
import org.openqa.selenium.By;
//import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
//import org.openqa.selenium.WebElement;
//import org.openqa.selenium.remote.DesiredCapabilities;
//import org.openqa.selenium.remote.RemoteWebDriver;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
//import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.testng.annotations.AfterTest;
import java.io.File;
import java.net.URL;
import java.net.MalformedURLException;
//import java.util.concurrent.TimeUnit;
//import org.junit.Test;
public class CustomerLogin {
AppiumDriver driver;
takeScreenshot SC;
#BeforeClass
public void setUp() throws MalformedURLException{
File app = new File(System.getProperty("user.dir")+ "\\apks\\DropCarOwner-STAGE-v2.1.0-rc.1.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("DeviceName","306SH");
capabilities.setCapability("PlatformValue", "4.4.2");
capabilities.setCapability("PlatformName", "Android");
capabilities.setCapability("app",app.getAbsolutePath());
driver= new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"),capabilities);
}*/
#Test
public void Login() throws Exception{
WebElement email= driver.findElement(By.id("com.dropcar.owner:id/editTextEmailAddress"));//com.dropcar.owner:id/editTextEmailAddress
email.sendKeys("a","w","a","i","s","d","u","r","r","a","n","i","8","7","#","g","m","a","i","l",".","c","o","m");
WebElement password= driver.findElement(By.id("com.dropcar.owner:id/editTextPassword")); //com.dropcar.owner:id/editTextPassword
password.sendKeys("c","h","e","c","k","i","n","g","1","2","3");
WebElement check= driver.findElement(By.name("Remember me")); //com.dropcar.owner:id/checkBoxRememberMe
driver.tap(0, check,0);
//check.click();
WebElement signIn=driver.findElement(By.name("SIGN IN"));
driver.tap(1,signIn,1);
//signIn.click();
SC.Screenshot(driver);
}
#AfterTest
public void end(){
driver.quit();
}
}
I am using Eclipse 4.4.1. How can I resolve this error?
Make sure before running the script appium-doctor command is working successfully. If you will attach the appium log then it will be more easy to tell you the actual solution of your problem.

Automation screenshot

I'm currently working on an automation project, I've created this simple program to report testing information and to take screenshots.
package ReportTest;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import ReportTest.Utitlity;
public class ReportTest {
ExtentReports report;
ExtentTest logger;
WebDriver driver;
#Test
public void verifyBlogTitle()
{
report =new ExtentReports("C:\\Users\\reganc3\\desktop\\report\\LearnAutomation.html");
logger=report.startTest("VerifyBlogTitle");
driver = new FirefoxDriver();
driver.manage().window().maximize();
logger.log(LogStatus.INFO, "Browser started");
driver.get("http://www.learn-automation.com");
logger.log(LogStatus.INFO, "Application is up and running");
String title = driver.getTitle();
Assert.assertTrue(title.contains("Selenium"));
logger.log(LogStatus.PASS, "Title Verified");
}
#AfterMethod
public void tearDown(ITestResult result)
{
if(result.getStatus()==ITestResult.FAILURE)
{
String screenshot_path = Utitlity.captureScreenshot(driver, result.getName());
logger.log(LogStatus.FAIL, "TitleVerification", screenshot_path);
}
report.endTest(logger);
report.flush();
driver.get("C:\\Users\\reganc3\\desktop\\report\\LearnAutomation.html");
}
}
Here is my Utilitys class which is being called to take the screenshot
package ReportTest;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import java.util.*;
public class Utitlity {
public static String captureScreenshot(WebDriver driver, String screenshotName)
{
try
{
TakesScreenshot ts=(TakesScreenshot)driver;
File source=ts.getScreenshotAs(OutputType.FILE);
String dest = " C:\\Users\\reganc3\\desktop\\ " +screenshotName+ ".png";
File destination=new File(dest);
FileUtils.copyFile(source, destination);
System.out.println("Screenshot taken");
return dest;
}
catch (Exception e)
{
System.out.println("Exception while taking screenshot "+e.getMessage());
return e.getMessage();
}
}
}
I am getting the following error
**Exception while taking screenshot null
I'm quite new to Selenium and TestNG so I'm basically looking for someone to shed some light on this and give me some pointers in the right direction and to understand what is actually happening with my code that's throwing this error.
Thank you In advance.
I'm currently using this method to take screenshots in my tests:
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
public void takeScreenShot(WebDriver driver, String methodName) {
File screenshotFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenshotFile,new
File("Screenshots\\"+methodName+" "+GetTimeStampValue()+".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
and this method to get a TimeStamp:
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
public String GetTimeStampValue()throws IOException{
Calendar cal = Calendar.getInstance();
Date time=cal.getTime();
String timestamp=time.toString();
String systime=timestamp.replace(":", "-");
return systime;
}
I was using the wrong version of ExtentReport for the code I had.
The code I was using was for a newer up to date version of ExtentReport and the maven dependency I had was pointing to an older version. The code itself worked perfectly when I updated the dependency to the newest version.
Robot r=new Robot();
r.keyPress(KeyEvent.VK_PRINTSCREEN);
r.keyRelease(KeyEvent.VK_PRINTSCREEN);

Automated testing using selenium with firefox browser

I downloaded the code below and used it for some tests and u=it ran yesterday but since today the code stopped working. My tests are failing now which was not happening before. It throws up an error saying org.openqa.selenium.ElementNotVisibleException: element is not currently visible so cannot interact with element.
package org.openqa.selenium.example;
//import org.openqa.selenium.browserlaunchers.locators.GoogleChromeLocator;
//import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
//import org.openqa.selenium.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
//import org.openqa.selenium.chrome.*;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.firefox.FirefoxDriver;
//import org.openqa.selenium.support.ui.Select;
//import org.openqa.selenium.net.UrlChecker;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class KongaUrlTest
{
private WebDriver driver;
private String baseUrl;
//private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception
{
driver = new FirefoxDriver();
baseUrl = "http://www.konga.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testFirefoxWebdriver() throws Exception
{
driver.get(baseUrl);
driver.findElement(By.cssSelector("a.vertnavlink > span")).click();
try
{
assertEquals("Phones & Tablets | Konga Nigeria", driver.getTitle());
System.out.println(driver.getTitle());
}
catch (Error e)
{
verificationErrors.append(e.toString());
}
}
#After
public void tearDown() throws Exception
{
System.out.println(driver.getCurrentUrl());
driver.quit();
}
}
There's a blocking dialog being displayed. It's probably displayed each time Selenium opens a new browser and navigates to that site. Close that dialog first:
driver.get(baseUrl);
try
{
driver.findElement(By.cssSelector(".fancybox-close")).click();
}
catch { }
driver.findElement(By.cssSelector("a.vertnavlink > span")).click();

Categories