Why getting resource list null for webpage when automating desktop application i.e. hybrid (Desktop and Web)? - selenium-webdriver

I am automating hybrid application i.e. Desktop and WebApplication. We have desktop application in which some of pages are integrated using WebPages and some one pages are in desktop application. Below is the code which I have used to open Desktop Application. And its opening the application successfully. But When I am going to print resource list size, it comes 'null' where locator for resourcelist is showing correct count in chrome browser. I can login successfully using winium driver instance. After logged in, list of resources are present which I integrated in webpage.
Let me know if I am doing wrong in given code?
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.winium.DesktopOptions;
import org.openqa.selenium.winium.WiniumDriver;
import org.openqa.selenium.winium.WiniumDriverService;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
public class VMSWiniumBaseDriver {
public WiniumDriver driver;
String applicationPath = "C:\\Users\\prashantn\\Downloads\\Publish\\ABC.exe";
#Parameters({ "windowsPlatform" })
#BeforeClass(alwaysRun = true)
public void initialize(String browser) throws IOException, InterruptedException {
if (browser.equalsIgnoreCase("desktop")) {
try {
WiniumDriverService service;
DesktopOptions option;
option = new DesktopOptions();
option.setApplicationPath(applicationPath);
File driverPath = new File(System.getProperty("user.dir") + File.separator + "driver" + File.separator
+ "Winium.Desktop.Driver.exe");
service = new WiniumDriverService.Builder().usingDriverExecutable(driverPath).usingPort(9999)
.withVerbose(true).withSilent(false).buildDesktopService();
try {
service.start();
} catch (IOException e) {
System.out.println("Exception while starting WINIUM service");
e.printStackTrace();
}
driver = new WiniumDriver(service, option);
} catch (Exception e) {
System.out.println(e);
}
}
}
#AfterClass(alwaysRun = true)
public void TeardownTest() {
if (null == driver) {
driver.close();
driver.quit();
}
}
public WiniumDriver getDriver() {
return driver;
}
}
Here is
CommonUtilities.Java
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.concurrent.ThreadLocalRandom;
import org.openqa.selenium.WebDriver;
import org.sikuli.hotkey.Keys;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
import org.sikuli.script.ScreenImage;
import dataproviders.VMSConfigFileReader;
import managers.VMSWiniumBaseDriver;
public class CommonUtilities extends VMSWiniumBaseDriver {
public WebDriver getWebDriverInstance() {
WebDriver webDriver = (WebDriver) driver;
return webDriver;
}
}
LoginPage.java
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.winium.WiniumDriver;
import utilities.CommonUtilities;
public class LoginPage{
#FindBy(id = "PART_EditableTextBox")
WebElement userName;
#FindBy(id = "TextBlock_Password")
WebElement passwordInput;
#FindBy(id = "LoginButton")
WebElement loginButton;
#FindBy(xpath = "//dd[contains(#class,'vms-tree-enabled')]/span[#class='vms-treeview-label'][#title!='Removed channels'][#title!='Unassociated']")
List<WebElement> resourcesList;
public void getResourcesList() {
CommonUtilities commonUtilities = new CommonUtilities();
// System.out.println("Page Source :: "+commonUtilities.getWebDriverInstance());
List<WebElement> list = commonUtilities.getWebDriverInstance().findElements(By.xpath(
"//dd[contains(#class,'vms-tree-enabled')]/span[#class='vms-treeview-label'][#title!='Removed channels'][#title!='Unassociated']"));
System.out.println("Resources Size :: " + list.size());
for (int i = 0; i < resourcesList.size(); i++) {
System.out.println("Resource Name :: " + resourcesList.get(i).getText());
}
}
}
Exception Log:
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebDriver.findElements(org.openqa.selenium.By)" because the return value of "utilities.CommonUtilities.getWebDriverInstance()" is null
at pageobjects.LoginPage.getResourcesList(LoginPage.java:57)
at testcases.AppLaunchTest.selectLayOutBasic1(AppLaunchTest.java:62)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:132)
at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:599)
at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:174)
at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:822)
at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:147)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.testng.TestRunner.privateRun(TestRunner.java:764)
at org.testng.TestRunner.run(TestRunner.java:585)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:384)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:378)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:337)
at org.testng.SuiteRunner.run(SuiteRunner.java:286)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1218)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
at org.testng.TestNG.runSuites(TestNG.java:1069)
at org.testng.TestNG.run(TestNG.java:1037)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

Related

Getting an error as while reading a JSON file containing 'Usernames' and 'Passwords' using TestNG DataProviders in Selenium

Getting an error as while reading a JSON file using TestNG DataProviders in Selenium.
Error:
class com.google.gson.JsonObject cannot be cast to class org.json.simple.JSONObject (com.google.gson.JsonObject and org.json.simple.JSONObject are in unnamed module of loader &apos;app&apos;)
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.google.gson.JsonParser;
import io.github.bonigarcia.wdm.WebDriverManager;
public class DataDrivenTest_json {
WebDriver driver;
#BeforeClass
void setUp() { /* to set up chromedriver */
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.MILLISECONDS);
}
#Test(dataProvider="dp") /* using dataproviders*/
void login(String data) {
String list[] = data.split(",");
driver.get("some website url");
driver.findElement(By.cssSelector("[id='Email']")).sendKeys(list[0]);//username
driver.findElement(By.cssSelector("[id='Password']")).sendKeys(list[1]);//password
driver.findElement(By.cssSelector("[type='submit']")).click();
}
#DataProvider(name="dp")
public String[] readJson() throws IOException{
#SuppressWarnings("deprecation")
JsonParser jsonparser = new JsonParser();
FileReader reader =new FileReader("C:\\Users\\dell\\eclipse-workspace-
photon\\ExcelDriven\\src\\test\\java\\Testdata.json");
#SuppressWarnings("deprecation")
Object obj = jsonparser.parse(reader); //java object
JSONObject userLoginsJsonObj = (JSONObject)obj;
JSONArray userLoginsArray =(JSONArray)userLoginsJsonObj.get("userLogins");
String array[] = new String[userLoginsArray.size()];
for(int i=0; i<userLoginsArray.size();i++) {
JSONObject users = (JSONObject)userLoginsArray.get(i);
String username = (String)users.get("username");
String password = (String)users.get("password");
array[i] = username+","+password;
}
return array;
}
#AfterClass
void tearDown() { //close driver
driver.close();
}
}
/*My MavenProject has testng included and pom.xml file has 'com.googlecode.json-simple' dependency added.Still the above error is visible in console.*/
You import class org.json.simple.JSONObject while you need to import com.google.gson.JsonObject. You cannot just cast an object to any class even if that class has the same name. The package of the class also matters.

Null Pointer Exception using TestNG

I am trying to automate and have integrated Selenium with Appium and I am using Eclipse with TestNG for execution.
Now within a project I have a package with two classes; the first class is for login into the App and the second class is for logout
First class code -
package com.gma.test;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class LoginApp {
public AppiumDriver driver;
#BeforeSuite
public void beforeMethod() throws InterruptedException {
File app = new File("C:\\Users\\mc30058\\Downloads\\gma-QA-RELEASE-QRCode-07022015_v4.5.4028.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("deviceName","Android Emulator");
capabilities.setCapability("platformVersion", "4.4");
capabilities.setCapability("app", app.getAbsolutePath());
try {
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
} catch (MalformedURLException e) {
e.printStackTrace();
}
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
driver.findElement(By.xpath("//android.widget.Button[#resource-id='com.mcdonalds.app:id/button_choose_closest']")).click();
driver.findElement(By.xpath("//android.widget.Button[#text='Continue']")).click();
driver.findElement(By.xpath("//android.widget.Button[#text='OK']")).click();
}
#Test (priority=1)
public void Login() {
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
driver.findElement(By.xpath("//android.widget.TextView[#text='Sign In']")).click();
driver.findElement(By.xpath("//android.widget.EditText[#resource-id='com.mcdonalds.app:id/signin_edittext_email']")).sendKeys("anuj.shrivastava#us.mcd.com");
driver.findElement(By.xpath("//android.widget.EditText[#resource-id='com.mcdonalds.app:id/signin_edittext_password']")).sendKeys("Anujtest2");
currentTime();
driver.findElement(By.xpath("//android.widget.Button[#text='Sign In']")).click();
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
driver.findElement(By.xpath("//android.widget.Button[#text='Yeah, count me in!']")).isDisplayed();
currentTime();
driver.findElement(By.xpath("//android.widget.Button[#text='No, thanks. I like to be out of the loop']")).click();
}
private void currentTime() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println( sdf.format(cal.getTime()) );
}
}
Second class code:
package com.gma.test;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Logout {
public AppiumDriver driver;
#Test (priority=3)
public void LogoutApp() {
driver.findElement(By.xpath("//android.widget.TextView[#content-desc='Navigation Button']")).click();
driver.findElement(By.xpath("//android.widget.TextView[#text='Sign Out']")).click();
driver.findElement(By.xpath("//android.widget.Button[#text='Sign Out']")).click();
}
}
Contents from Testng.xml
<suite name = "GMA Automation">
<test name = "GMA Automation">
<classes>
<class name = "com.gma.test.LoginApp"/>
<class name = "com.gma.test.Logout"/>
</classes>
</test>
</suite>
I receive Null Pointer exception after execution of first class. Appium server stops saying no more commands received. Please help.
You are getting NPE b'coz you have declared one more driver reference public AppiumDriver driver; in your Logout class.
And you are using this driver reference without instantiation.
In logout class you forget to instantiate your AppiumDriver driver.
try this:
public AppiumDriver driver;
driver = new AndroidDriver();

the method get(class <ReportClass>) is undefined for the type ExtentReport

i'm making selenium extent report but i'm getting error on - static final ExtentReports extrpt=ExtentReports.get(ReportClass.class);
after mouse hover on get i'm getting below info.
the method get(class ) is undefined for the type ExtentReports
it's my simple java project please tell me where am i doing mistake.
package DemoPacakge;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.ExtentReports;
public class ReportClass {
// * ReportClass .class will become TheClassName.class
static final ExtentReports extrpt=ExtentReports.get(ReportClass.class);
public void test()
{
WebDriver driver =new FirefoxDriver();
driver.get("http://learn-automation.com/advance-selenium-reporting-with-screenshots/");
String tile=driver.getTitle();
Assert.assertTrue(tile.contains("learn"));
}
}
Please see the examples section: http://extentreports.relevantcodes.com/1x/docs.html#examples
There are a few errors such as, you are not initializing the report with a "file-path". You have not instructed Extent to start a test either. Try with the below code, it should work:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.LogStatus;
public class ReportClass {
static final ExtentReports extrpt = ExtentReports.get(ReportClass.class);
WebDriver driver;
#BeforeClass
public void beforeClass() {
extrpt.init("file-path.html", true);
extrpt.config().displayCallerClass(false);
}
#Test
public void test() {
extrpt.startTest("Test");
driver = new FirefoxDriver();
extrpt.log(LogStatus.INFO, "Starting FirefoxDriver..");
driver.get("http://learn-automation.com/advance-selenium-reporting-with-screenshots/");
extrpt.log(LogStatus.INFO, "Navigating to learn-automation.com..");
String title = driver.getTitle();
extrpt.log(LogStatus.INFO, "Title: " + title);
try {
Assert.assertTrue(title.contains("learn"));
extrpt.log(LogStatus.PASS, "Step Passed");
}
catch (AssertionError e) {
extrpt.log(LogStatus.FAIL, "<pre>" + e.getMessage() + "</pre>");
}
}
#AfterTest
public void afterTest() {
driver.quit();
extrpt.endTest();
}
}

unable to launch internet explorer in TestNG

I am new in TestNG. This is my code which I tried in eclipse, but there is a problem occurring in launching internet explorer.
The error it is giving is
org.openqa.selenium.remote.SessionNotFoundException: Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones. Enable Protected Mode must be set to the same value (enabled or disabled) for all zones. (WARNING: The server did not provide any stacktrace information)
This is the complete code....
package com.tcs.medmantra;
import java.io.File;
import java.io.IOException;
import java.util.Set;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class Registration {
WebDriver driver;
WebElement element;
WebElement element2;
WebDriverWait waiter;
#Test(priority = 1)
public void register_With_Cash() throws RowsExceededException, BiffException, WriteException, IOException
{
driver=new InternetExplorerDriver();
driver.get("https://172.25.155.250/loginpage.aspx");
//((JavascriptExecutor)driver).executeScript("window.resizeTo(1366, 768);");
waiter = new WebDriverWait (driver, 40);
driver.findElement(By.id("txtuname")).sendKeys("122337");
driver.findElement(By.name("txtpwd")).sendKeys("Tcs!#345");
driver.findElement(By.id("btnsubmit")).click();
sleep(25000);
//print URL
String url = driver.getCurrentUrl();
System.out.println(url);
}
#BeforeTest
public void beforeTest() {
File file = new File("D:\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
}
#AfterTest
public void afterTest() {
driver.quit();
}
}
As the error says you need set the protected mode same for all zones, either enabled or disabled. Preferred would be enabled. See here
Change your code to include the path for InternetExplorerDriver.
File file = new File("C:/Selenium/iexploredriver.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driver = new InternetExplorerDriver();

Selenium Web driver--Failure Screenshot is not captured in TestNG report

With below mentioned code,if the test case is pass-screenshot captured successfully and displayed in report.But when the test is failed--screenshot is not displayed.Even screenshot hyperlink is not displayed in report.Anybody can sort out the mistake in code?
package listeners;
import java.io.File;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;
import java.util.logging.Logger;
#Listeners
public class CountryChoserLayer extends TestListenerAdapter {
#Test(priority=1)
public void choseCountry() throws Exception{
driver.findElement(By.id("intselect")).sendKeys("India");
driver.findElement(By.xpath(".//*[#id='countryChooser']/a/img")).click();
//window.onbeforeunload = null;
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
FileUtils.copyFile(scrnsht, new File(NewFileNamePath));
System.out.println(NewFileNamePath);
Reporter.log("Passed Screenshot");
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case-Success");
System.out.println("---------------------------------------");
}
public String baseurl="http://www.sears.com/shc/s/CountryChooserView?storeId=10153&catalogId=12605";
public WebDriver driver;
public int Count = 0;
#Test(priority=0)
public void openBrowser() {
driver = new FirefoxDriver();
driver.manage().deleteAllCookies();
driver.get(baseurl);
}
#Test(priority=2)
public void closeBrowser() {
driver.quit();
}
#Override
public void onTestFailure(ITestResult result){
Reporter.log("Fail");
System.out.println("BBB");
//Reporter.setCurrentTestResult(result);
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//File scrFile = ((TakesScreenshot) WebDriver.globalDriverInstance).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
//System.out.println("AAA" + NewFileNamePath);
try {
//System.out.println("CCC");
FileUtils.copyFile(scrnsht,new File(NewFileNamePath));
System.out.println(NewFileNamePath);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("DDD");
e.printStackTrace();
}
Reporter.log("Failed Screenshot");
Reporter.setCurrentTestResult(null);
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case Failed");
System.out.println("---------------------------------------");
}
#Override
public void onTestSkipped(ITestResult result) {
// will be called after test will be skipped
Reporter.log("Skip");
}
#Override
public void onTestSuccess(ITestResult result) {
// will be called after test will pass
Reporter.log("Pass");
}
}
Your onTestFailure method is not being called because you didn't specify listener for your test class. You are missing a value in #Listeners annotation. It should be something like
#Listeners({CountryChoserLayer.class})
You can find more ways of specifying a listener in official TestNg's documentation.
Another problem you are likely to encounter would be NullPointerException while trying to take screenshot in onTestFailure method. The easiest workaround for that would be changing the declaration of driver field to static. I run the code with those fixes and I got the report with screenshot.
I must add that in my opinion putting both test and listener methods into one class is not a good practice.

Resources