Selenium : Unable to identify object using data provider - java

Beginner in this space, appreciate your help on the problem!
I'm trying to script a path
Login
create new user
log out
Login method works fine
Create user is dependent on Login method to be completed, using data providers and post login to create new user
Issue is after logging in the elements/objects in create user class are not identified. I have tried it using different element finders and browsers. Appreciate if you help around
Project Structure is
Project
Package1
Logindataprovider.class
newaccountDataProvider.class
Package2
LoginpageObjects.class
NewAccountPageObjects.class
Package3
LoginTestscripts.class
NewAccountTestScript.class
LoginTestscripts- Class
LoginPageObjects LgnObj = new LoginPageObjects();
#Test(groups = { "Logingroup1" }, dataProvider = "LoginCred", dataProviderClass = LoginDataProviders.class)
public void mytest(String DDUname, String DDpwd,String ExpLoginPage, int Browsertype) {
LgnObj.setBrowser(Browsertype);
Logger log = Logger.getLogger(LoginDataProviders.class);
log.info("Login To application method");
LgnObj.init();
// Login page assertion actual values
String LoginPageAssertactual = LgnObj.LoginPageAssertionActual();
//Login page assertion
Assert.assertEquals(LoginPageAssertactual, ExpLoginPage);
//login to application
LogginCommonProcess(DDUname, DDpwd, LgnObj);
}
public void LogginCommonProcess(String DDUname, String DDpwd,
LoginPageObjects LgnObj) {
LgnObj.enterUserName(DDUname);
LgnObj.enterPassword(DDpwd);
LgnObj.Loginbtn();
LgnObj.enterPIN();
LgnObj.CompanyName();
}
Logindataprovider- Class
public class LoginPageObjects {
WebDriver driver;
public void setBrowser(int type) {
if (type == 1) {
driver = new FirefoxDriver();
} else if (type == 2) {
String path = ClassLoader.getSystemResource("chromedriver.exe")
.getPath();
System.setProperty("webdriver.chrome.driver", path);
driver = new ChromeDriver();
} else if (type == 3) {
String path = ClassLoader.getSystemResource("IEDriverServer.exe")
.getPath();
System.setProperty("webdriver.ie.driver", path);
driver = new InternetExplorerDriver();
}
}
public void init() {
driver.manage().window().maximize();
driver.navigate().to("https://test2.qatest.com/Login.aspx");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
public String LoginPageAssertionActual() {
String LoginPageAssertionact = driver.findElement(By.tagName("h1"))
.getText();
return LoginPageAssertionact;
}
public void enterUserName(String DDUname) {
driver.findElement(By.id("ctl00_MainContent_usernameField")).sendKeys(
DDUname);
}
public void enterPassword(String DDpwd) {
driver.findElement(By.id("ctl00_MainContent_passwordField")).sendKeys(
DDpwd);
}
New User- page object
public class NewUser {
WebDriver driver;
public void setup() {
System.out.println("Start here");
System.setProperty("webdriver.ie.driver", "C:\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.manage().window().maximize();
driver.navigate().to("https://test2.directorsdesk.com/Login.aspx");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
public void setBrowser(int type) {
if (type == 1) {
driver = new FirefoxDriver();
} else if (type == 2) {
String path = ClassLoader.getSystemResource("chromedriver.exe")
.getPath();
System.setProperty("webdriver.chrome.driver", path);
driver = new ChromeDriver();
} else if (type == 3) {
String path = ClassLoader.getSystemResource("IEDriverServer.exe")
.getPath();
System.setProperty("webdriver.ie.driver", path);
driver = new InternetExplorerDriver();
} else if (type == 4) {
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setBrowserName("chrome");
cap.setVersion("38");
cap.setPlatform(Platform.WINDOWS);
try {
driver = new RemoteWebDriver(new URL(
"http://127.0.0.1:4444/wd/hub"), cap);
} catch (MalformedURLException e) {
// log erro unable to access remote system, running in local
// firefox
driver = new FirefoxDriver();
}
}
}
**public void ManageSystem() {
driver.findElement(By.partialLinkText("Manage System")).click();
driver.findElement(By.linkText("Manage System")).click();
}**
public class NewAccount {
#Test(dataProvider = "UserDetails", dataProviderClass = LoginDataProviders.class, dependsOnGroups = "Logingroup1")
public void CreateNewAccount(String Emailid, String Firstname,
String Lastname, String PrimaryEmailid, int browserType) {
NewUser NewUserObj = new NewUser();
NewUserObj.setBrowser(browserType);
**NewUserObj.ManageSystem();** // Fails here
NewUserObj.UserAccounts();
NewUserObj.NewUserAccount();
NewUserObj.Emailid(Emailid);
NewUserObj.UserFirstname(Firstname);
NewUserObj.UserLastname(Lastname);
NewUserObj.PrimaryEmai(PrimaryEmailid);
NewUserObj.SaveAccountSettings();
LoginPageObjects LgnPgObj = new LoginPageObjects();
LgnPgObj.Logout();
LgnPgObj.closeBrowser();
}

Have you tried this:
public void entityFieldIsEntered(String field, String value) {
WebElement valueElem = new SharedDriver().findElement(By.xpath("(.//*[text()='" + field
+ ":'])[2]/parent::*/span/input"));
valueElem.sendKeys(new CharSequence[] { value });
}
assuming you are using input wrapper in your html. This code search for text label on the screen, then goes to its parent and navigate to input field.

If you are going to use multiple page objects in one test, you will need to share the same driver between those page objects.
Try creating a separate setupDriver class and have each page object take a driver parameter to be constructed.
At the beginning of each test setup the driver, then pass in the driver as you create each object.

Related

Cannot invoke "org.openqa.selenium.JavascriptExecutor.executeScript(String, Object[])" because "jse" is null

Any idea why I get NullPointerException here. Error - java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.JavascriptExecutor.executeScript(String, Object[])" because "jse" is null
I am trying to input date (disabled field). Tests are running on Android.
This is a page object model framework with cucumber ,appium and Java.
**Base Class**
public AppiumDriver<MobileElement> driver;
public AppiumDriver<MobileElement> getDriver() {
return driver;
}
public void setDriver(AppiumDriver<MobileElement> driver) {
this.driver = driver;
}
public SignInPage getSignIn1() {
return signInPage;
}
public SignUpPage getSignUpPage() {
return signUpPage;
}
public AccountPage getAccountPage() {
return accountPage;
}
public void initializeObject(AppiumDriver<MobileElement> driver) {
signInPage = new SignInPage(driver);
signUpPage = new SignUpPage(driver);
accountPage = new AccountPage(driver);
public void driverSetUp() throws Exception {
DesiredCapabilities cap = new DesiredCapabilities();
ConfigInfo config = ConfigInfo.instance();
if(config.platform.equals(platformName.ANDROID.name()) & (config.context.equals(context.ANDROIDWEB.name())))
{
cap.setCapability("deviceName", config.emulatorAndroidDeviceName);
cap.setCapability("udid", config.emulatorAndroidUdid);
cap.setCapability("platformName", config.emulatorAndroidPlatformName);
cap.setCapability(MobileCapabilityType.BROWSER_NAME,"Chrome");
cap.setCapability("platformVersion", config.emulatorAndroidPlatformVersion);
cap.setCapability("chromedriverExecutable",config.chromeexecutables);
cap.setCapability("appium:chromeOptions", ImmutableMap.of("w3c", false));
driver = new AndroidDriver<>(url, cap);
setDriver(driver);
initializeObject(driver);
driver.get(config.appURL);
}
Sign up Class
public class SignUp {
public AppiumDriver<MobileElement> driver;
BaseSetUp baseSetUp;
public SignUp(BaseSetUp baseSetUp) {
this.baseSetUp = baseSetUp;
}
#Then("I select the date from the calendar")
public void i_select_the_date_from_the_calandar() throws Exception {
try {
int[] currentDate = baseSetUp.currentDate();
String date=currentDate[1]+"/"+currentDate[2]+"/"+currentDate[0];
System.out.println(date);
MobileElement element = baseSetUp.getSurveyPage().CalendarInput; // This is the date input field
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].value('value', '" + date +"')", element);
} catch (Exception e) {
System.out.println(e);
}
}

Cucumber Selenium - Java - PageFactory : Step Definition: java.lang.NullPointerException

Hi community: I'm facing the next issue: I'm working with Cucumber, Selenium WebDriver using Page Factory. The error getting here is from the Step Definition side:
java.lang.NullPointerException
at pages.page_First.startNavigation(page_First.java:33)
at stepdefs.stepdefs_First.iGoToGoogle(stepdefs_First.java:20)
at ✽.I go to Google (file:src/test/resources/features/first.feature:10)
This is the part of the code (StepDefinition) where issue occurs:
#Given("I go to Google")
public void iGoToGoogle() {
page_first.startNavigation();
}
From the Page side, this is the code:
public class page_First extends BasePage {
public page_First() {
PageFactory.initElements(driver, this);
}
///////////////////////WEB ELEMENTS///////////////////////
#FindBy(name = "q")
private WebElement searchText;
#FindBy(name="btnK")
private WebElement searchButton;
//////////////////////BASE METHODS//////////////////////
public void startNavigation() {
driver.get(PropertyManager.getInstance().getURL());
}
public void search(String search) {
setTextAs(searchText, search);
}
public void enterButton (){
clickElement(searchButton);
}
}
The feature file:
Scenario Outline: Search google.com to verify google search is working
Given I go to Google
When I query for "<search>" cucumber spring selenium
And click search
Then google page title should become the first page
Examples:
| search |
| Cucumber Selenium |
This is my Browser class:
public class Browser {
// Take the instance of WebDriver
public static WebDriver driver;
public WebDriver initializeBrowser() throws IOException {
//Properties taken from config.properties
String browser = PropertyManager.getInstance().getBrowser();
if(browser.equals("chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
} else if(browser.equals("firefox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
} else if(browser.equals("ie")) {
WebDriverManager.iedriver().setup();
driver = new InternetExplorerDriver();
} else if(browser.equals("edge")) {
WebDriverManager.edgedriver().setup();
driver = new EdgeDriver();
} else if(browser.equals("opera")) {
WebDriverManager.operadriver().setup();
driver = new OperaDriver();
} else {
System.setProperty("webdriver.safari.driver","/usr/bin/safaridriver");
driver = new SafariDriver();
}
System.out.println("-----> Proceed to initialize driver <-----");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
return driver;
}
}
and here is my configuration property reader class:
public class PropertyManager {
private static PropertyManager instance;
private static final Object lock = new Object();
private static String propertyFilePath = System.getProperty("user.dir") + "//src//main//resources//data//config.properties";
///////////////////////////// DATA IN PROPERTIES //////////////////////////
private static String url;
private static String browser;
//Create a Singleton instance. We need only one instance of Property Manager.
public static PropertyManager getInstance () {
if (instance == null) {
synchronized (lock) {
instance = new PropertyManager();
instance.loadData();
}
}
return instance;
}
//Get all configuration data and assign to related fields.
private void loadData() {
//Declare a properties object
Properties prop = new Properties();
//Read config.properties file
try {
prop.load(new FileInputStream(propertyFilePath));
} catch (IOException e) {
System.out.println("Configuration properties file cannot be found");
}
//Get properties from config.properties
url = prop.getProperty("url");
browser = prop.getProperty("browser");
}
public String getURL () {
return url;
}
public String getBrowser () {
return browser;
}
}
I was forgetting this, my Step Definition class:
public class stepdefs_First {
private page_First page_first = PageFactory.initElements(Browser.driver, page_First.class);
#Given("I go to Google")
public void iGoToGoogle() {
page_first.startNavigation();
}
#When("I query for {string} cucumber spring selenium")
public void iQueryForCucumberSpringSelenium(String search) throws Exception {
page_first.search(search);
}
#And("click search")
public void clickSearch() {
page_first.enterButton();
}
#Then("google page title should become the first page")
public void googlePageTitleShouldBecomeTheFirstPage() {
System.out.println("All OK");
}
}
By the way, this is my config.properties
browser = firefox
url = https://www.google.cl
Please I need your help.
Initialize the Page Object class
page_First page_first=new page_First();

Storing initialized drivers in a Java List but appearing null on fetching them

In my selenium code in Java I have to use multiple drivers. So I am declaring them in the class and storing them in a list. Then in a method I am initializing them but when I fetching them using get(index function) I am getting their value as null but if I use them directly then value is appearing. See Below:
Here I am declaring my drivers:
public static WebDriver driver1 = null;
public static WebDriver driver2 = null;
public static WebDriver driver3 = null;
public static WebDriver driver4 = null;
public static WebDriver driver5 = null;
public static WebDriver driver6 = null;
Now I am storing them in a list just after that:
public List<WebDriver> Drivers = Arrays.asList(driver1, driver2, driver3, driver4, driver5, driver6);
Then in a method I am initializing the drivers which is called from my tests.
public void initializeDrivers(String driver) throws InterruptedException, AWTException, IOException {
if(driver.equals("driver1") && driver1==null) {
System.out.println("First browser is opening");
driver1 = getDriver();
} else if(driver.equals("driver2") && driver2==null) {
System.out.println("Second browser is opening");
driver2 = getDriver();
} else if(driver.equals("driver3") && driver3==null) {
System.out.println("Third browser is opening");
driver3 = getDriver();
System.out.println("Login with qa softphone 1");
SFLP.softphoneLogin(driver3, CONFIG.getProperty("qa_test_site_name"), CONFIG.getProperty("qa_user_3_username"), CONFIG.getProperty("qa_user_3_password"));
//setDefaultSetting(driver3);
} else if(driver.equals("driver4") && driver4==null) {
System.out.println("Fourth browser is opening");
driver4 = getDriver();
} else if(driver.equals("driver5") && driver5==null) {
System.out.println("Fifth browser is opening");
driver5 = getDriver();
} else if(driver.equals("driver6") && driver6==null) {
System.out.println("Sixth browser is opening");
driver6 = getDriver();
}
}
Code for getDriver:
public WebDriver getDriver() {
WebDriver driver = null;
ChromeOptions options = new ChromeOptions();
if(System.getProperty("os.name").contains("Windows")){
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\src\\test\\resources\\ChromeDriver\\chromedriver.exe");
}
options.addArguments("--test-type");
options.addArguments("--start-maximized");
options.addArguments("--use-fake-device-for-media-stream");
options.addArguments("--use-fake-ui-for-media-stream");
//Initializing a driver
driver = new ChromeDriver(options);
return driver;
}
Now when I fetch drivers directly as driver1 then I am getting the driver in it but when I fetch it using the list Drivers.get(1) I get value as null. Any help is well appreciated. Thanks in advance.
Update your code as given below.
Change 1: Drivers should be static.
public static List<WebDriver> Drivers = Arrays.asList(driver1, driver2, driver3, driver4, driver5, driver6);
Change 2:
public void initializeDrivers(String driver) throws InterruptedException, AWTException, IOException {
if(driver.equals("driver1") && driver1==null) {
System.out.println("First browser is opening");
driver1 = getDriver();
Drivers.set(0, driver1);
} else if(driver.equals("driver2") && driver2==null) {
System.out.println("Second browser is opening");
driver2 = getDriver();
Drivers.set(1, driver2);
} else if(driver.equals("driver3") && driver3==null) {
System.out.println("Third browser is opening");
driver3 = getDriver();
Drivers.set(2, driver3);
System.out.println("Login with qa softphone 1");
SFLP.softphoneLogin(driver3, CONFIG.getProperty("qa_test_site_name"), CONFIG.getProperty("qa_user_3_username"), CONFIG.getProperty("qa_user_3_password"));
//setDefaultSetting(driver3);
} else if(driver.equals("driver4") && driver4==null) {
System.out.println("Fourth browser is opening");
driver4 = getDriver();
Drivers.set(3, driver4);
} else if(driver.equals("driver5") && driver5==null) {
System.out.println("Fifth browser is opening");
driver5 = getDriver();
Drivers.set(4, driver5);
} else if(driver.equals("driver6") && driver6==null) {
System.out.println("Sixth browser is opening");
driver6 = getDriver();
Drivers.set(5, driver6);
}
}

Selenium GRID Test execution

I am trying hard to run my Selenium Test not local but in a grid.
I thought I am doing good but I don´t get it to run.
HUB and NODE are Up and running(started with CMD) and I am using the right IP adresses.
Please let me know what I am doing wrong! Do you think it maybe could be a problem with a proxy?
Greetings Arno (student from Germany)
// Import all the stuff I need
public class MpreisScreenshot_ID {
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#BeforeClass(alwaysRun = true)
public void setUp() throws Exception {
String requiredBrowser = "firefox";
}
//the "if" underneath is just for a selection (to make it better to read
// I deleted the others)
if (requiredBrowser == "firefox")
{
DesiredCapabilities capabilityFirefox = DesiredCapabilities.firefox();
capabilityFirefox.setBrowserName("firefox");
capabilityFirefox.setVersion("54");
WebDriver driver= new RemoteWebDriver(new
URL("http://***.***.***.**:4445/grid/register"),capabilityFirefox);
}
baseUrl = "http://*****/****";
// driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
WebDriver driver;
#Test
public void captureScreenshot() throws Exception
{
//Start of Selenium test
// Maximize the browser
driver.manage().window().maximize();
// deleted all the steps
#AfterMethod
public void tearDown(ITestResult result)
{
// Test failing or Passing?
if(ITestResult.FAILURE==result.getStatus())
{
try
{
// Create reference of TakesScreenshot
TakesScreenshot ts=(TakesScreenshot)driver;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
String uhrzeit= sdf.format(timestamp);
// Call method to capture screenshot
File source=ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File("D:\\DATA\\Selenium\\TestNG-
Screenshots\\"+result.getName()+uhrzeit+".png"));
System.out.println("Screenshot taken");
}
catch (Exception e)
{
System.out.println("Exception while taking screenshot "+e.getMessage());
}
}
// close application
driver.quit();
}
}
Check your url, usually the default port for the Selenium Hub is 4444, also try the following:
http://youripaddress:4444/wd/hub/

How can i send multiple test data using testng in to following

Please suggest me how to sent 3 users in 3 browsers for this field
driver.findElement(By.id(PropertiesConfiguration.getMyProperty("PinTextfield"))).sendKeys(PropertiesConfiguration.getMyProperty("user"));
// main class
public class TestHRWW {`main class`
protected WebDriver driver;
#Parameters("browser")`parameter for browser initialization`
#BeforeClass
public void setup(String browser) {
if (browser.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();
} else if (browser.equalsIgnoreCase("iexplorer")) {
System.setProperty("webdriver.ie.driver","Drivers\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
} else if (browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver","Drivers\\chromedriver.exe");
driver = new ChromeDriver();
}
else {
throw new IllegalArgumentException("The Browser Type is Undefined");
}
driver.manage().window().maximize();
}
#BeforeMethod
public void open() {
driver.get("http://www.myhrasiapacific.com/");
}
#AfterClass
public void teardown() {
try {
driver.quit();
} catch (Exception e) {
driver = null;
}
}
// sub class
public class Login extends TestHRWW {`sub class`
String x;
static Logger logger = Logger.getLogger(Login.class.getName());
#Test
public void ClickLogon(WebDriver driver) throws InterruptedException, IOException {
driver.findElement(`enter code here`
By.id(PropertiesConfiguration.getMyProperty("logonbutton")))
.click();
Thread.sleep(2000);
// here i need to sent 3 differt users credentials
driver.findElement(
By.id(PropertiesConfiguration.getMyProperty("PinTextfield")))
.sendKeys(PropertiesConfiguration.getMyProperty("user"));
Thread.sleep(2000);
driver.findElement(
By.id(PropertiesConfiguration
.getMyProperty("passwordTextfield"))).sendKeys(
PropertiesConfiguration.getMyProperty("password"));
Thread.sleep(2000);
driver.findElement(
By.id(PropertiesConfiguration.getMyProperty("loginbutton")))
.click();
driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
}
}
You shall use TestNG #DataProvider to pass username & passwords
your login method will be like
#Test(dataProvider="dataForLogin")
public void ClickLogon(String userName,String password) {
}
#DataProvider(name="dataForLogin")
public static Object[][] prepareDataForLogin(){
// preparation of login data
}
If you are using QAF then you don't need to manually parse your json data and get rid from data provider class.
public class tDataHelper {
private static List<String> studentsToCreate = new ArrayList<String>();
static void parseData() throws Exception {
studentsToCreate.add("user1");
studentsToCreate.add("user2");
studentsToCreate.add("user3");
}
#DataProvider
public static Object[][] createStudents() {
Object[][] objArray = new Object[studentsToCreate.size()][];
for (int i = 0; i < studentsToCreate.size(); i++) {
objArray[i] = new Object[1];
objArray[i][0] = studentsToCreate.get(i);
}
return objArray;
}
}
public class testStudents {
private static tDataHelper helper = new tDataHelper();
#BeforeClass
public void setup() throws Exception {
tDataHelper.parseData();
}
#Test(dataProvider = "createStudents", dataProviderClass = tDataHelper.class)
public void testCreateStudents(String studentsToCreate) {
System.out.println(studentsToCreate);
}
}
QAF Test Data Driven

Categories

Resources