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

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();

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);
}
}

Parallel execution does not work in Selenium Page object Model

I'm doing automation with Selenium - Page object Model & TestNG & Java. I have 2 testcases in 2 class files and i want to run all my tests in parallel
I passed driver and test object to all my pages.
When running my testng.xml with parallel="classes" two browser windows opened and only in one window, tests is running. The other window is closed. Eclipse showed me Null pointer exception.
Answer:
Later i understood that this is about usage of static in ExtentReport initialization. I corrected my code in reporter class.
Test Class-1:
public class CreateXCase extends SeleniumBase
{
#BeforeTest(alwaysRun=true )
public void setTestDetails()
{
author = System.getProperty("user.name");
testcaseName="Verify that X case is successfully created";
testcaseDec = "Create X Case";
category="Regression";
}
#Test(priority=2,groups = {"Regression"})
public void createCaseWithNewParticipants() throws Exception
{
new LoginPage(driver, test).login().quickNavigation_CASE()
.navigateToCreateCase().enterApplicantInformation()
.navigateToCaseSection().createCase();
}
}
Test Class-2:
public class CreateYcase extends SeleniumBase
{
#BeforeTest(alwaysRun=true )
public void setTestDetails()
{
author = System.getProperty("user.name");
testcaseName="Verify that Y case is successfully created";
testcaseDec = "Create Y Case";
category="Regression";
}
#Test(priority=1,groups = {"Regression"})
public void createCaseWithNewParticipants() throws Exception
{
new LoginPage(driver,test).login().quickNavigation_CASE()
.navigateToCreateCase().enterApplicantInformation()
.navigateToCaseSection().createCase();
}
SeleniumBase.java:
public class SeleniumBase extends Reporter implements Browser, Element
{
public static WebDriverWait wait;
#BeforeMethod(alwaysRun=true )
public void configureAndLaunch() throws IOException
{
driver = startApp(ReadPropertyFile.get("Browser"), ReadPropertyFile.get("URL"));
}
#Override
#AfterMethod (alwaysRun=true )
public void closeBrowser()
{
driver.quit();
}
#Override
public RemoteWebDriver startApp(String browser, String url)
{
try
{
if (browser.equalsIgnoreCase("chrome"))
{
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
driver = new ChromeDriver();
}
else if (browser.equalsIgnoreCase("firefox"))
{
System.setProperty("webdriver.gecko.driver", "./drivers/geckodriver.exe");
driver = new FirefoxDriver();
}
else if (browser.equalsIgnoreCase("ie"))
{
System.setProperty("webdriver.ie.driver", "./drivers/IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
driver.get(url);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
return driver;
}
catch (Exception e)
{
int a = e.toString().indexOf("Exception:");
String str = e.toString().substring(0, a + 30);
System.out.println(str + "Exception captured");
System.err.println("The Browser Could not be Launched. Hence Failed");
}
finally
{
takeSnap();
}
return null;
}
Reporter.java:
public abstract class Reporter {
public RemoteWebDriver driver;
public ExtentHtmlReporter reporter;
public static ExtentReports extent;
public ExtentTest test;
public String testcaseName, testcaseDec, author ;
public String category="";
public static String excelFileName;
public static String extentreportpath;
#BeforeSuite (alwaysRun=true )
public void startReport(ITestContext c) throws IOException
{
String reportName=this.getClass().getName().substring(29, 33).toUpperCase() +" Screen Test Report";
String screenName=this.getClass().getName().substring(29, 33).toUpperCase() +" Tests";
String rptName="h5{font-size: 0px;}h5::after{content:\'"+screenName+"\';font-size: 1.64rem; line-height: 110%;margin: 0.82rem 0 0.656rem 0;}";
String suiteName = c.getCurrentXmlTest().getSuite().getName();
if (suiteName.contains("Default suite")||suiteName.contains("Failed suite"))
suiteName ="";
extentreportpath="./reports/"+suiteName+"Report.html";
reporter = new ExtentHtmlReporter(extentreportpath);
reporter.setAppendExisting(true);
extent = new ExtentReports();
extent.attachReporter(reporter);
reporter.loadXMLConfig(new File("./Resources/extent-config.xml"));
reporter.config().setTheme(Theme.DARK);
reporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
reporter.config().setReportName(reportName);
reporter.config().setCSS(rptName);
}
#BeforeClass(alwaysRun=true )
public ExtentTest report()
{
test = extent.createTest(testcaseName, testcaseDec);
test.assignAuthor(author);
return test;
}
public abstract long takeSnap();
public void reportStep(String desc,String status,boolean bSnap)
{
MediaEntityModelProvider img=null;
if(bSnap && !status.equalsIgnoreCase("INFO"))
{
long snapNumber=100000L;
snapNumber=takeSnap();
try
{
img=MediaEntityBuilder.createScreenCaptureFromPath("./../reports/images/"+snapNumber+".jpg").build();
}
catch(IOException e)
{
}
}
if(status.equalsIgnoreCase("pass"))
{
//test.pass(desc,img);
test.log(Status.PASS, desc, img);
}
else if(status.equalsIgnoreCase("fail"))
{
//test.fail(desc,img);
test.log(Status.FAIL, desc, img);
}
else if(status.equalsIgnoreCase("INFO"))
{
//test.pass(desc);
test.log(Status.INFO, desc,img);
}
}
public void reportStep(String desc,String status)
{
reportStep(desc,status,true);
}
#AfterSuite (alwaysRun=true )
public void stopReport() throws Exception
{
extent.flush();
}
}
Making the ExtentReport variable 'extent' as static solved my issue.
Eg: public static ExtentReports extent;
I modified the code in my question also.
Since i have only one #Test in a class, parallel="methods" is of no use in my case.

What am i missing here in pagefactory during initializing the page objects? Getting NullpointerException during element identification

I have setup page object model and trying to initialize the web objects using PageFactory.
I have initialized my driver in testBase and extended the page class to this testbase. When I try to run my test case, the below nullpointerexeception is thrown
TestBase.java
public class testBase {
public WebDriver driver;
public static Properties prop;
public FlightBookingPage FBPage;
public testBase(){
try {
prop = new Properties();
FileInputStream ip = new FileInputStream(System.getProperty("user.dir")+ "/src/main/java"
+ "/Config/config.properties");
prop.load(ip);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void setDriverPath() {
if (PlatformUtil.isMac()) {
System.setProperty("webdriver.chrome.driver", "chromedriver");
driver = new ChromeDriver();
}
if (PlatformUtil.isWindows()) {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
driver = new ChromeDriver();
}
if (PlatformUtil.isLinux()) {
System.setProperty("webdriver.chrome.driver", "chromedriver_linux");
driver = new ChromeDriver();
}
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(testUtil.PAGE_LOAD_TIMEOUT, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(testUtil.IMPLICIT_WAIT, TimeUnit.SECONDS);
}
The below code is actual test class which calls the appropriate functions and variables from page class
public class FlightBookingTest extends testBase {
#BeforeMethod
public void setup() {
FBPage = new FlightBookingPage();
setDriverPath();
driver.get(prop.getProperty("url"));
}
#Test
public void testThatResultsAppearForAOneWayJourney() {
FBPage.clickOneWayBtn();
FBPage.typeOriginCity("Bangalore");
FBPage.selectOriginCityfromList("Bangalore");
FBPage.typeDestinCity("Delhi");
FBPage.selectDestinCityfromList("Delhi");
FBPage.selectDate();
FBPage.clickSearch();
// verify that result appears for the provided journey search
Assert.assertTrue(isElementPresent(By.className("searchSummary")));
}
#AfterMethod
public void tearDown() {
// close the browser
driver.quit();
}
Below is the page class for the above test
public class FlightBookingPage extends testBase {
// Page Factory - OR:
#FindBy(id = "OneWay")
public WebElement oneWayRdBtn;
#FindBy(id = "FromTag")
public WebElement fromCitytxtbox;
#FindBy(xpath = "//*[#id='ui-id-1']/li")
public List<WebElement> originOptionList;
#FindBy(id = "toTag")
public WebElement toCitytxtbox;
#FindBy(xpath = "//*[#id='ui-id-2']/li")
public List<WebElement> destinOptionList;
#FindBy(xpath = "//*[#id='ui-datepicker-div']/div[1]/table/tbody/tr[3]/td[7]/a")
public WebElement date;
#FindBy(id = "SearchBtn")
public WebElement searchBtn;
#FindBy(className = "searchSummary")
public WebElement searchResultsHeadertxt;
// Initializing the Page Objects:
public FlightBookingPage(){
PageFactory.initElements(driver, this);
}
public void clickOneWayBtn() {
oneWayRdBtn.click();
}
public void typeOriginCity(String origin) {
fromCitytxtbox.clear();
fromCitytxtbox.sendKeys(origin);
}
public void selectOriginCityfromList(String origin) {
for (WebElement list : originOptionList) {
if (list.getText().contains(origin)) {
list.click();
break;
}
}
}
public void typeDestinCity(String destin) {
toCitytxtbox.clear();
toCitytxtbox.sendKeys(destin);
}
public void selectDestinCityfromList(String destin) {
for (WebElement list : destinOptionList) {
if (list.getText().contains(destin)) {
list.click();
break;
}
}
}
public void selectDate() {
date.click();
}
public void clickSearch() {
searchBtn.click();
}
public WebElement verifySearchSummaryHeader() {
return searchResultsHeadertxt;
}
}
I am getting the below error message as soon the focus turns to this block
public void clickOneWayBtn() {
oneWayRdBtn.click();
}
java.lang.NullPointerException
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy9.click(Unknown Source)
at Pages.FlightBookingPage.clickOneWayBtn(FlightBookingPage.java:45)
at FlightBookingTest.testThatResultsAppearForAOneWayJourney(FlightBookingTest.java:24)
Kindly change the below line of code in testBase class
public WebDriver driver;
To
public static WebDriver driver;
Try below in Page class:
In your page class kindly create a constructor
WebDriver driver;
public FlightBookingPage(WebDriver driver) {
this.driver = driver;
}
Swapped the position of initiation of new FlightBookingPage and setDriverPath(). It worked.
Updated code below:
#BeforeMethod
public void setup() {
setDriverPath();
FBPage = new FlightBookingPage();
driver.get(prop.getProperty("url"));
}
Please try swapping your FBPage = new FlightBookingPage(); and
setDriverPath(); so that value of driver will be instantiated.
Change your code to:
#BeforeMethod
public void setup() {
setDriverPath();
FBPage = new FlightBookingPage();
driver.get(prop.getProperty("url"));
}

Selenium : Unable to identify object using data provider

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.

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