NullPointer Exception: Using PageFactory Design Pattern for Appium - nullpointerexception

I am trying to use PageFactory Design Pattern but getting Null Pointer Exception.Please suggest any improvement required.
My Sample code looks like:
public DriverCapabilities() throws IOException{
URL url;
try {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("newCommandTimeout", "90");
caps.setCapability("browserName", "");
caps.setCapability("appActivity",Config.appActivity );
caps.setCapability("appPackage", Config.appPackage);
caps.setCapability("appWaitActivity",Config.appWaitActivity);
caps.setCapability("platformName", "Android");
caps.setCapability("platformVersion", "5.0");
caps.setCapability("deviceName", "Android Emulator");
}
caps.setCapability("app", Config.path);
caps.setCapability("appium-version", "1.3.7.2");
url = new URL("http://127.0.0.1:4723/wd/hub");
innerDriver = Config.os.equalsIgnoreCase("ANDROID")? new AndroidDriver(url, caps): new IOSDriver(url, caps);
DriverWait.implicitWait();
PageFactory.initElements(new AppiumFieldDecorator(innerDriver, 5, TimeUnit.SECONDS), this);
}
Sample Screen Class:
public class DemoScreen{
#AndroidFindBy(id = "eula_accept")
private static RemoteWebElement eula;
public static void submit() throws IOException{
init.getInstance(); //To initialize the driver
getEula().click();
}
public static WebElement getEula() {
return eula;
}
}
Sample Test code:
public class Demo1{
#Test(groups={"smokeTest"})
public void test1() throws IOException {
DemoScreen.submit();
}*
Is it because somewhere I'm not initializing the object or has it to do with the design pattern I'm following?

Related

How can I use Desktop automation?

I tried Winium but xpath is not working. Is there anything besides Winium?
public class Desktop_Steps {
public static void main (String[] args) throws MalformedURLException, InterruptedException {
DesktopOptions option = new DesktopOptions();
option.setApplicationPath("location of app");
URL url = new URL(" http://127.0.0.1:4723/");
WiniumDriver driver = new WiniumDriver(url,option);
// driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
Thread.sleep(7000);
driver.findElement(By.id("15894400")).sendKeys("hello");
}
}

NullPointerException error i.e. AndroidDriver not gets initialized for the second test class as It's working fine for the first test class

This is My setup class:
public class SetupClass {
//AppiumDriver<MobileElement> driver;
AndroidDriver<MobileElement> d;
public Properties prop =null;
public File file;
public FileInputStream fis;
#Parameters(value ="Android")
#BeforeSuite
public void setup(String Android) throws IOException, Exception{
LoadPropertiesFile();
DesiredCapabilities caps = new DesiredCapabilities();
/*caps.setCapability("plateformName", "Android");
caps.setCapability(CapabilityType.PLATFORM_NAME, "Android");*/
if (Android.equalsIgnoreCase("Moto_g4_Plus")) {
caps.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
caps.setCapability(MobileCapabilityType.PLATFORM_VERSION, "7.0");
caps.setCapability(MobileCapabilityType.UDID, "ZY223WZSQ9");
caps.setCapability(MobileCapabilityType.DEVICE_NAME, "Moto G4 Plus");
}
caps.setCapability("app", "C:\\Users\\amarjeet.sharma\\eclipse-workspace\\com.asm.app\\src\\test\\resources\\app\\asmVisit.apk");
caps.setCapability("appPackage", "com.sumasoft.net.asmscheduler");
caps.setCapability("appActivity", "md5f32326382a711c73d2de951d70f3bd5e.MainActivity");
caps.setCapability("autoGrantPermissions", true);
URL url;
try {
url = new URL("http://127.0.0.1:4723/wd/hub");
//driver = new AppiumDriver<MobileElement>(url, caps);
d = new AndroidDriver<MobileElement>(url, caps);
Thread.sleep(5000);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
System.out.println("Cause is:" +e.getCause());
System.out.println("Message is:" +e.getMessage());
e.printStackTrace();
}
}
public void LoadPropertiesFile() throws IOException {
prop=new Properties();
file =new File(System.getProperty("user.dir")+"/src/main/resources/config.properties");
fis=new FileInputStream(file);
prop.load(fis);
//System.out.println(prop.getProperty("userId"));
}
//#AfterTest
public void TearDown() throws IOException{
System.out.println("Quit");
d.quit();
}
}
This is My LoginTest
public class LoginTest extends SetupClass{
#Test(priority = 1)
public void login() throws Exception {
LoginPage lp = new LoginPage(d);
//System.out.println(prop.getProperty("userId"));
lp.userName(prop.getProperty("userId"));
Thread.sleep(500);
lp.password(prop.getProperty("Passwd"));
Thread.sleep(500);
lp.loginButton();
}
}
And this is my create new journey class
public class AddJourneyTest extends SetupClass{
#Test(priority=2)
public void AddNewJourney() throws Exception {
AddjourneyPage addobj = new AddjourneyPage(d);
addobj.ClicktoAdd();
addobj.SelectFromToDate();
addobj.SelectState();
addobj.SelectCity();
addobj.ClickonSubmit();
}
}
I am getting NullPointerException for AddJourney class
I think when I run it as TestNG then the driver gets initiated for the LoginTest and holds the control. So that AddJourney class does not get driver initiated and hence getting NullPointerException.
I am using Appium Server, Java + Selenium + TestNG for the Android Application automation on Windows system with physical android device.
Maybe I am wrong. But I am not getting solution over it. Please help.

How can I run the same test on browserstack and local browsers?

I've set up NUnit tests that runs on BrowserStack (set up from this example https://github.com/browserstack/nunit-browserstack )
Base class:
namespace Bloc.TestProject
{
public class BrowserStackNUnitTest
{
protected IWebDriver driver;
protected string profile;
protected string environment;
private Local browserStackLocal;
public BrowserStackNUnitTest(string profile, string environment)
{
this.profile = profile;
this.environment = environment;
}
[SetUp]
public void Init()
{
...
Browserstack tests:
namespace Bloc.TestProject
{
[TestFixture("parallel", "chrome")]
[TestFixture("parallel", "ie11")]
[TestFixture("parallel", "iphoneX")]
[TestFixture("parallel", "ipad")]
[TestFixture("parallel", "samsungGalaxyS8")]
[Parallelizable(ParallelScope.Fixtures)]
public class OnTimeOnlineBooking : BrowserStackNUnitTest
{
WebDriverWait wait;
public OnTimeOnlineBooking(string profile, string environment) : base(profile, environment)
{
}
... my tests ...
Local tests:
namespace Bloc.TestProject
{
[TestFixture(typeof(PhantomJSDriver))]
public class LocalBrowserTest<TWebDriver> where TWebDriver : IWebDriver, new()
{
private IWebDriver driver;
[SetUp]
public void CreateDriver()
{
this.driver = new TWebDriver();
}
[TearDown]
public void Cleanup()
{
driver.Quit();
}
... my tests ...
Is there any way I can structure my tests so that I can run a test and it'll run both locally and on browserstack without having to duplicate the test code?
I can Suggest a workaround for this case in Java, needs to change in C#.
write the code of browser-stack setup
public static browserstack_setup() {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("browserName", "chrome");
caps.setCapability("version", "");
caps.setCapability("platform", "windows");
caps.setCapability("os_version", "8.1");
WebDriver driver = new RemoteWebDriver(new URL(URL), caps);
driver.get("http://www.google.com");
}
then write code for launch browser
public void openbrowser(String browsername, String URL){
if(browsername.equalsIgnoreCase("broserstack")){
browserstack_setup();
}else if(browsername.equalsIgnoreCase("CH")){
System.setProperty("webdriver.chrome.driver",chromedriverpath);
driver=new ChromeDriver();
driver.get(URL);
}
}
You may fetch the name from test context and based on that information, launch the local driver or remote driver. For the repo and you example, I assume the below code should work. You may also want to look at other APIs available under TestContext.CurrentContext.Test for your comparison operation
[SetUp]
public void Init()
{
if(TestContext.CurrentContext.Test.Name == "MyTestName"){
this.driver = new TWebDriver();
}
else{
NameValueCollection caps = ConfigurationManager.GetSection("capabilities/" + profile) as NameValueCollection;
NameValueCollection settings = ConfigurationManager.GetSection("environments/" + environment) as NameValueCollection;
DesiredCapabilities capability = new DesiredCapabilities();
foreach (string key in caps.AllKeys)
{
capability.SetCapability(key, caps[key]);
}
foreach (string key in settings.AllKeys)
{
capability.SetCapability(key, settings[key]);
}
String username = Environment.GetEnvironmentVariable("BROWSERSTACK_USERNAME");
if(username == null)
{
username = ConfigurationManager.AppSettings.Get("user");
}
String accesskey = Environment.GetEnvironmentVariable("BROWSERSTACK_ACCESS_KEY");
if (accesskey == null)
{
accesskey = ConfigurationManager.AppSettings.Get("key");
}
capability.SetCapability("browserstack.user", username);
capability.SetCapability("browserstack.key", accesskey);
if (capability.GetCapability("browserstack.local") != null && capability.GetCapability("browserstack.local").ToString() == "true")
{
browserStackLocal = new Local();
List<KeyValuePair<string, string>> bsLocalArgs = new List<KeyValuePair<string, string>>();
bsLocalArgs.Add(new KeyValuePair<string, string>("key", accesskey));
browserStackLocal.start(bsLocalArgs);
}
driver = new RemoteWebDriver(new Uri("http://"+ ConfigurationManager.AppSettings.Get("server") +"/wd/hub/"), capability);
}
}
You need to ensure you have specified test fixtures for running on Local and Grid. For example, if test A on Safari on Grid and test A on local browser

Selenium webdriver - action.sendkeys() : notworking

I'm trying to test one specific Selenium's Actions class method, which is as below.
public Actions sendKeys(java.lang.CharSequence... keysToSend)
Sends keys to the active element. This differs from calling WebElement.sendKeys(CharSequence...) on the active element.
public class Demo_1 {
private WebDriver driver;
private Actions action;
private String baseUrl;
#Before
public void setUp() throws Exception {
File file = new File("C:\\Users\\ProgramFiles\\firefox.exe");
FirefoxProfile profile = new FirefoxProfile();
FirefoxBinary binary = new FirefoxBinary(file);
driver = new FirefoxDriver(binary, profile);
action = new Actions(driver);
baseUrl = "http://www.mortgagecalculator.org";
}
#Test
public void testUntitled() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.name("param[homevalue]")).click();
driver.findElement(By.name("param[homevalue]")).clear();
action.sendKeys("300000");
}
#After
public void tearDown() throws Exception {
//driver.quit();
}
}
I can do this alternatively, but in some cases when there is no WebElement, action.sendKeys can help to send CharSequence without any WebElement as parameter.
Can some come up with similar kind of issue, as the above code is not working :(
Cause its Actions class object so you need to tell the driver the actions you are performing.
action.sendKeys("300000").perform();
Will do the needful.

Exception in thread "main" java.lang.NullPointerException in Selenium Webdriver

class Login as the following method Kreato_Login():-
public void Kreato_Login(){
driver = new FirefoxDriver();
baseUrl = "https://testrugtn.kreatocrm.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit. SECONDS);
driver.manage().window().maximize();
driver.get(baseUrl + "/");
driver.findElement(By. id("Login_txtUserName")).clear();
driver.findElement(By. id("Login_txtUserName")).sendKeys( "saravana");
driver.findElement(By. id("Login_txtPassword")).clear();
driver.findElement(By. id("Login_txtPassword")).sendKeys( "5678");
driver.findElement(By. id("Login_btnLogin")).click();
}
Class Lead as the following method "Lead_MandatoryCheck()":-
LoginLogout leadInstance=new LoginLogout();
public void Lead_MandatoryCheck() throws InterruptedException{
leadInstance.Kreato_Login();
driver1.findElement(By. xpath("//a[contains(text(),'Customers')]")).click();
driver1.findElement(By. linkText("Leads")).click();
//Add New
driver1.findElement(By. cssSelector( "#ctl00_ContentPlaceHolder1_cbpSubContent_imgAddNew_CD > span.dx-vam" )).click();
Thread.sleep(3000);
//Save
driver1.findElement(By. cssSelector("#ctl00_ContentPlaceHolder1_cbpAssociationNew_btnNewItemTopCreationSave_CD > span.dx-vam" )).click();
String mandatoryPopup= driver1.switchTo().alert().getText();
driver1.switchTo().alert().accept();
System.out.println(mandatoryPopup);
}
I try to call the above methods from the class Trigger as follows:-
public class TriggerClass {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
/*LeadCreation lc= new LeadCreation();
lc.setUp();
lc.testLeadCreation();
lc.tearDown();*/
LeadModule Lm=new LeadModule();
Lm.Lead_MandatoryCheck();
}
when i run the "Trigger.class"
Exception in thread "main" java.lang.NullPointerException
at workflow.LeadModule.Lead_MandatoryCheck(LeadModule.java:132)
at workflow.TriggerClass.main(TriggerClass.java:13)
This is how you should structure your class, members and functions:
TriggerClass.java:
public class TriggerClass {
public static WebDriver driver;
public static void main(String[] args) throws Exception {
driver = new FirefoxDriver();
LeadModule Lm=new LeadModule();
Lm.Lead_MandatoryCheck();
}
LeadModule.java:
public class LeadModule {
public WebDriver driver;
public LeadModule() {
this.driver = TriggerClass.driver;
}
public void Lead_MandatoryCheck() throws InterruptedException{
LoginLogout leadInstance = new LoginLogout();
leadInstance.Kreato_Login();
driver.findElement(By.xpath("//a[contains(text(),'Customers')]")).click();
driver.findElement(By.linkText("Leads")).click();
//Add New
driver.findElement(By.cssSelector( "#ctl00_ContentPlaceHolder1_cbpSubContent_imgAddNew_CD > span.dx-vam" )).click();
Thread.sleep(3000);
//Save
driver.findElement(By. cssSelector("#ctl00_ContentPlaceHolder1_cbpAssociationNew_btnNewItemTopCreationSave_CD > span.dx-vam" )).click();
String mandatoryPopup= driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
System.out.println(mandatoryPopup);
}
LoginLogout.java:
public class LoginLogout extends LeadModule {
public void Kreato_Login(){
baseUrl = "https://testrugtn.kreatocrm.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit. SECONDS);
driver.manage().window().maximize();
driver.get(baseUrl + "/");
driver.findElement(By.id("Login_txtUserName")).clear();
driver.findElement(By.id("Login_txtUserName")).sendKeys("saravana");
driver.findElement(By.id("Login_txtPassword")).clear();
driver.findElement(By.id("Login_txtPassword")).sendKeys("5678");
driver.findElement(By.id("Login_btnLogin")).click();
}
}
Your Java/Selenium basics are not clear. Please read through the documentation or view related tutorials on YouTube.