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

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.

Related

Unable to load chrome/gecko driver after using Cucumber Driver Factory

This is my first question ever asked here, so I hope I ask it the right way:
I'm working on a multimodule maven project to test a software that is still in a development. I've been using Cucumber, Selenium, JUnit for some time and doing online courses to improve my skills. In one of the tutorials was explained how to use Driver Factory and configuration files so I applied it to my project, but after that was unable to run any of the drivers (gecko/chrome/ie). Here is a big part of the code, so I hope someone can help :)
I catch the exception from the DriverFactory.class:
"Unable to load browser: null"
config.properties file has only one line:
browser=chrome
public class DriverFactory {
public static WebDriver driver;
public WebDriver getDriver() {
try {
//Read Config
ReadConfigFile file = new ReadConfigFile();
String browserName = file.getBrowser();
switch (browserName) {
case "firefox":
if (driver == null) {
System.setProperty("webdriver.gecko.driver", Constant.GECKO_DRIVER_DIRECTORY);
FirefoxOptions options = new FirefoxOptions();
options.setCapability("marionette", false);
driver = new FirefoxDriver(options);
driver.manage().window().maximize();
}
break;
case "chrome":
if (driver == null) {
System.setProperty("webdriver.chrome.driver", Constant.CHROME_DRIVER_DIRECTORY);
driver = new ChromeDriver();
driver.manage().window().maximize();
}
break;
/*case "ie":
if (driver == null) {
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
System.setProperty("webdriver.ie.driver", Constant.IE_DRIVER_DIRECTORY);
capabilities.setCapability("ignoreZoomSetting", true);
driver = new InternetExplorerDriver(capabilities);
driver.manage().window().maximize();
}
*/
}
} catch (Exception e) {
System.out.println("Unable to load browser: " + e.getMessage());
} finally {
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
}
return driver;
}
public class ReadConfigFile {
protected InputStream input = null;
protected Properties prop = null;
public ReadConfigFile() {
try {
input = ReadConfigFile.class.getClassLoader().getResourceAsStream(Constant.CONFIG_PROPERTIES_DIRECTORY);
prop = new Properties();
prop.load(input);
} catch(IOException e) {
e.printStackTrace();
}
}
public String getBrowser() {
if(prop.getProperty("browser") == null) {
return "";
}
return prop.getProperty("browser");
}
public class Constant {
public final static String CONFIG_PROPERTIES_DIRECTORY = "properties\\config.properties";
public final static String GECKO_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\resources\\geckodriver.exe";
public final static String CHROME_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\resources\\chromedriver.exe";
public class CreateCaseSteps extends DriverFactory {
//Background Steps
#Given("^user accesses the login page$")
public void userAccessesTheLoginPage() throws Throwable {
getDriver().get("http://localhost:8080/");
}
#When("^user enters a valid username")
public void userEntersAValidUsername(DataTable table) throws Throwable {
Thread.sleep(3000);
List<List<String>> data = table.raw();
getDriver().findElement(By.xpath("//input[#placeholder='username']")).sendKeys(data.get(0).get(0));
}
#When("^user enters a valid password")
public void userEntersAValidPassword(DataTable table) throws Throwable {
Thread.sleep(3000);
List<List<String>> data = table.raw();
getDriver().findElement(By.xpath("//input[#placeholder='password']")).sendKeys(data.get(0).get(0));
}
#And("^user clicks on the login button$")
public void userClicksOnTheLoginButton() throws Throwable {
getDriver().findElement(By.xpath("//input[#value='Login']")).click();
}
#Then("^user should be taken successfully to the login page$")
public void userShouldBeTakenSuccessfullyToTheLoginPage() throws Throwable {
Thread.sleep(3000);
WebElement logoutMenu = getDriver().findElement(By.xpath("//i[#class='glyphicon glyphicon-user']"));
Assert.assertEquals(true, logoutMenu.isDisplayed());
}

Extent Reports tests always reporting Pass

I am having an issue where if I run a test that has 6 steps, 3 pass, 1 fail, 2 skipped. It will always report as Passed in my extent reports. I am using Klov. Is it possible that I have not correctly configured the report? and if so does anyone have suggestions to fix this issue.
public class MyRunner {
#BeforeClass
public static void initialize(){
d = new Date();
ExtentProperties extentProperties = ExtentProperties.INSTANCE;
extentProperties.setKlovServerUrl("http://localhost");
extentProperties.setKlovProjectName("Test Project");
extentProperties.setKlovReportName("Test Report: " + d);
extentProperties.setMongodbHost("localhost");
extentProperties.setMongodbPort(27017);
extentProperties.setMongodbDatabase("klov");
}
}
#AfterClass
public static void teardown(ITestResult result){
extent.flush();
}
}
And here is my test, it is just a simple test that opens googles login page, just to make sure the extent reports will do everything I need it to
public class Google {
WebDriver driver;
#Given("^that I am on the webpage Google$")
public void thatIAmOnTheWebpageGoogle() throws Throwable {
System.setProperty("webdriver.chrome.driver","\\\\hiscox.nonprod\\profiles\\Citrix\\XDRedirect\\CaseyG\\Desktop\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("https://accounts.google.com/signin/v2/identifier?hl=en&passive=true&continue=https%3A%2F%2Fwww.google.com%2F&flowName=GlifWebSignIn&flowEntry=ServiceLogin");
driver.manage().window().maximize();
MyRunner.logger.log(Status.INFO, "Opened Google login page")
//throw new PendingException();
//extent.createTest("Step 1").pass("log");
}
#When("^I try to login$")
public void i_try_to_login() throws Throwable {
// find the username field and enters the username, then clicks next
WebElement username = driver.findElement(By.xpath("//input[#id='identifierId']"));
username.sendKeys("********");
driver.findElement(By.id("identifierNext")).click();
//finds the password field and enters the password
WebElement password = driver.findElement(By.xpath("//input[#name='password']"));
password.sendKeys("**********");
Assert.assertFalse(true);
driver.findElement(By.id("passwordNext")).click();
//throw new PendingException();
//extent.createTest("Step 2").pass("log");
}
#Then("^I will be successfully logged into Google$")
public void i_will_be_successfully_logged_into_Google() throws Throwable {
String account = "Google Account: greg casey \n" + "(klovtest#gmail.com)";
//WebElement loggedInUser = driver.findElement(By.xpath("//*[#id="gbw"]/div/div/div[2]/div[4]/div[1]"))
//*[#id="gbw"]/div/div/div[2]/div[4]/div[1]/a
//extent.createTest("Step 3").pass("log");
throw new PendingException();
}
}
You should use ITestListener Interface on your Listener class where extent report's test is created
OnTestStart and do other things alos as descriobed below (I have used Thread for parallel device testing so you can ignore, rest is useful)
public class Listeners extends Utilities implements ITestListener {
ExtentReports extent = ExtentReporterTool.getReport();enter code here
ExtentTest test;
ThreadLocal<ExtentTest> testObjects = new ThreadLocal<ExtentTest>();
#Override
public void onTestStart(ITestResult result) {
test = extent.createTest(result.getMethod().getMethodName());
testObjects.set(test);
}
#Override
public void onTestSuccess(ITestResult result) {
testObjects.get().log(Status.PASS, "Test Case passed");
}
#Override
public void onTestFailure(ITestResult result) {
testObjects.get().fail(result.getThrowable());
WebDriver driver;
try {
driver = (WebDriver) result.getTestClass().getRealClass().getSuperclass().getField("driver")
.get(result.getInstance()); testObjects.get().addScreenCaptureFromPath(takeScreenshot(result.getMethod().getMethodName(), driver),
result.getMethod().getMethodName());
} catch (IOException | IllegalArgumentException | SecurityException | IllegalAccessException
| NoSuchFieldException e) {
e.printStackTrace();
}
}
#Override
public void onTestSkipped(ITestResult result) {
testObjects.get().log(Status.SKIP, "Test Case skipped");
}
#Override
public void onFinish(ITestContext context) {
extent.flush();
}
}

NullPointer Exception: Using PageFactory Design Pattern for Appium

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?

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.

Selenium WebDriver, How to run/connect next class

I'm new to Selenium Webdriver, I have a few question :
First, I have 2 class, 'Login.java' and 'SelectCity.java
Class 1 : Login.java
invalidLogin
validLogin
Class 2 : SelectCity.java
For now, in Login.java I wrote
#After
public void tearDown() throws Exception {
driver.close();
}
which mean the browser will closed after finish run right?
Here is my question :
How to make after I run validLogin, it will continue to run the next class (SelectCity.java)?
Is it possible to do that?
How to make last browser (which test valid login) didn't get close?
My current Login.java class :
public class Login extends SelectCityAfterLogin{
private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://mysite/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testLoginInvalidPass() throws Exception {
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("user1");
driver.findElement(By.id("txtPassword")).sendKeys("somePassword");
driver.findElement(By.id("lbLogin")).click();
try {
assertEquals("Invalid User or Password", driver.findElement(By.id("lblError")).getText());
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
#Test
public void testLoginInvalidUsername() throws Exception {
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("username");
driver.findElement(By.id("txtPassword")).sendKeys("somepassword");
driver.findElement(By.id("lbLogin")).click();
try {
assertEquals("Invalid User or Password", driver.findElement(By.id("lblError")).getText());
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
#Test
public void testLoginNoUsername() throws Exception {
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("");
driver.findElement(By.id("txtPassword")).sendKeys("somePassword");
driver.findElement(By.id("lbLogin")).click();
try {
assertEquals("Please fill username and password.", driver.findElement(By.id("lblError")).getText());
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
#Test
public void testLoginNoPassword() throws Exception {
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("username");
driver.findElement(By.id("txtPassword")).sendKeys("");
driver.findElement(By.id("lbLogin")).click();
try {
assertEquals("Please fill username and password.", driver.findElement(By.id("lblError")).getText());
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
#Test
public void testLoginValid() throws Exception{
//SelectRoleAfterLogin selectRole = SelectRoleAfterLogin();
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("myUsername");
driver.findElement(By.id("txtPassword")).sendKeys("password");
driver.findElement(By.id("lbLogin")).click();
Thread.sleep(3000);
}
}
Thx
Yes you can run selectcity after login
You should Extend your First class to Second class
In your Login.java extend it to selectcity java like below
Public class login extends Selectcity {
After your validlogin
create a new instance for selectcity (If you are using #test, create the below in that)
selectcity test = new selectcity()
Once after your valid login do the following
test.(will fetch you the methods available in selectcity.java)
By this way you can call once class to another.
Let me know if this helps
UPDATE :
if selectcityAfterlogin in public class Login extends **SelectCityAfterLogin** is your second class name, then you are creating an incorrect object i guess
In your public login class please check whether your are extending the proper second class name
In #test method
#Test
public void testLoginValid() throws Exception{
//SelectRoleAfterLogin selectRole = SelectRoleAfterLogin();
it should be
SelectCityAfterLogin selectrole = new SelectCityAfterLogin()
selectrole.(will fetch you the methods of second city)
Please let me know if this helps.
One better solution would be to create multiple methods than multiple #test. You can call these to single #test suite.
I am assuming, you have 2 classes 'Login.java' and 'SelectCity.java'
as follows:
Class 1 : Login.java
public void invalidLogin (WebDriver driver){
//some operations
}
public void validLogin (WebDriver driver){
//some operations
}
Class 2 : SelectCity.java
public void selectCity (Webdriver Driver){
//some operations
}
Class 3: LoginAndSelectCity.java
public static void main(String args []){
WebDriver driver = new FirefoxDriver();
Login.validLogin(driver);
SelectCity.selectCity(driver);
}
If all classes should be in same package then only it works else you need to import packages or create new child to do inheritance of the classes.