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.
Related
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();
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"));
}
i am Unable to Have separate Logs/entries for Different Test Cases. i.e Logs are Getting Appended on to a Single Test Case in the Extent Report generated.
Using Extent Report Version 2.41.1..
The Report Sample:
MY Code Goes like This:
Base Class of TestNG:
public static ExtentReports report;
public static ExtentTest logger;
#BeforeSuite
#Parameters({"BrowserName"})
public void beforeSuite(#Optional("Firefox") String BrowserName)
{
date = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("dd-MM-yyyy");
String TodaysDate = ft.format(date);
prop = ResourceBundle.getBundle("DataFile");
Driver = Browser_Factory_FSQA_Class.getBrowser(BrowserName);
path = "//home//workspace//....//FSQA.ExtentReports//FSQA_ExtentReport_" + TodaysDate;
File f=new File(path);
if(!f.exists())
{
report = new ExtentReports(path);
}
}
#BeforeTest
#Parameters({"BrowserName"})
public void SetUpConfig(#Optional("Firefox") String BrowserName)
{
report = new ExtentReports(path, false,DisplayOrder.NEWEST_FIRST);
report.loadConfig(new File("//home//......//extent-config.xml"));
report.addSystemInfo("Build-Tag", prop.getString("Build-Tag"))
.addSystemInfo("Selenium ", prop.getString("SelVer"))
.assignProject(prop.getString("Application"))
.addSystemInfo("Envirnoment", prop.getString("AppEnvirnoment"))
.addSystemInfo("Extent", prop.getString("ExtRpVer"));
logger = report.startTest(this.getClass().getSimpleName());
logger.log(LogStatus.INFO,this.getClass().getSimpleName() +" will Run on "+ BrowserName +" Browser");
Driver.get(prop.getString("URL"));
Driver.manage().window().maximize();
Driver.manage().window().maximize();
Driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
}
#AfterMethod(alwaysRun=true)
public void afterMethod(ITestResult result) throws IOException
{
try
{
if(result.getStatus()==ITestResult.FAILURE)
{
String res = captureScreenshot(Driver, result.getName());
String image= logger.addScreenCapture(res);
System.out.println(image);
String TestCaseName = this.getClass().getSimpleName() + " Test Case Failure and Title/Boolean Value Failed";
logger.log(LogStatus.FAIL, TestCaseName + logger.addScreenCapture(res));
}
else if(result.getStatus()==ITestResult.SUCCESS)
{
logger.log(LogStatus.PASS, this.getClass().getSimpleName() + " Test Case Success and Title Verified");
}
else if(result.getStatus()==ITestResult.SKIP)
{
logger.log(LogStatus.SKIP, this.getClass().getSimpleName() + " Test Case Skipped");
}
}
catch(Throwable t)
{
logger.log(LogStatus.ERROR,t.getMessage());
}
}
public String captureScreenshot(WebDriver Driver, String TestName)
{
try
{
date = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("dd_MM_yyyy");
String TodaysDate = ft.format(date);
TakesScreenshot ts=(TakesScreenshot)Driver;
File source=ts.getScreenshotAs(OutputType.FILE);
Sc_Destination = prop.getString("SC_Dest")+TestName+"__"+TodaysDate+".png";
FileUtils.copyFile(source,new File(Sc_Destination));
logger.log(LogStatus.FAIL,image, "Title verification");*/
return Sc_Destination;
}
catch (Exception e)
{
System.out.println("Exception while taking screenshot "+e.getMessage());
}
return Sc_Destination;
}
#AfterTest(alwaysRun=true)
public void AfterTest()
{
Driver.close();
report.endTest(logger);
report.flush();
}
#AfterSuite
public void AfterSuite()
{
report.close();
Driver.quit();
}
My Tests are Separate Clases which Extends this Base Class:
TC1:
public classTC1 extends BaseTestNG
{
#Test(groups = {"Happy_Path"} , description="TC1")
public void TestCase1() throws InterruptedException, Exception
{
logger.log(LogStatus.INFO, " Test Case2 Block Entered");
Thread.sleep(4000);
......
......
logger.log(LogStatus.INFO, "Assert Flag Received");
Thread.sleep(4000);
Assert.assertTrue(AssertFlag);
}
}
TC2:
public classTC2 extends BaseTestNG
{
#Test(groups = {"Happy_Path"} , description="TC2")
public void TestCase2() throws InterruptedException, Exception
{
logger.log(LogStatus.INFO, " Test Case2 Block Entered");
Thread.sleep(4000);
......
......
logger.log(LogStatus.INFO, "Assert Flag Received");
Thread.sleep(4000);
Assert.assertTrue(AssertFlag);
}
}
I am Using POM Classes along with TestNG and running the Testcases using testng.xml.
I am able to generate the Extent Report but unable to Differentiate Between TC1 & TC2 Logs i.e all test Case logs are getting appended to single TestCase as shown in the Above Screen Shot.
I want each Test Case Logs/Entry in separate rows in the Extent Reports.
Can Anyone please rectify the mistake in my code and help me out.
Thanks in Advance!!!
I think, you should initialize your logger in BeforeMethod and use report.flush() in AfterMethod. That may solve your problem.
NOW: I have test project. Using maven-failsave-plugin I run jetty, then deploy there war and execute test scripts.
TODO: I need to run in parallel in 5 webdrivers one method same time.
Or execute the same test class in 5 drivers same time.
It's like performance testing using Selenium ( bad choice, but it's requirement).
Thats how looks my ParrallelParametrized class.
public class ParallelParametrized extends Parameterized {
private static class ThreadPoolScheduler implements RunnerScheduler {
private ExecutorService executor;
public ThreadPoolScheduler() {
String threads = System.getProperty("web.driver.amount");
int numThreads = Integer.parseInt(threads);
executor = Executors.newFixedThreadPool(numThreads);
}
#Override
public void finished() {
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
} catch (InterruptedException exc) {
throw new RuntimeException(exc);
}
}
#Override
public void schedule(Runnable childStatement) {
executor.submit(childStatement);
}
}
public ParallelParametrized(Class klass) throws Throwable {
super(klass);
setScheduler(new ThreadPoolScheduler());
}
public void filter(Filter filter) throws NoTestsRemainException {
super.filter(new FilterDecorator(filter));
}
private static class FilterDecorator extends Filter {
private final Filter delegate;
private FilterDecorator(Filter delegate) {
this.delegate = delegate;
}
#Override
public boolean shouldRun(Description description) {
return delegate.shouldRun(wrap(description));
}
#Override
public String describe() {
return delegate.describe();
}
}
private static Description wrap(Description description) {
String name = description.getDisplayName();
String fixedName = deparametrizedName(name);
Description clonedDescription =
Description.createSuiteDescription(fixedName,description.getAnnotations().toArray(new Annotation[0]));
for(Description child : description.getChildren()){
clonedDescription.addChild(wrap(child));
}
return clonedDescription;
}
private static String deparametrizedName(String name) {
if(name.startsWith("[")){
return name;
}
int indexOfOpenBracket = name.indexOf('[');
int indexOfCloseBracket = name.indexOf(']')+1;
return name.substring(0,indexOfOpenBracket).concat(name.substring(indexOfCloseBracket));
}
}
And that is my Abstact Test Class
public abstract class AbstractParallelBaseTest {
public static ThreadLocal<WebDriver> CURRENT_DRIVER = new ThreadLocal<WebDriver>();
public static List<WebDriver> DRIVERS_TO_CLEANUP = Collections.synchronizedList(new ArrayList<WebDriver>());
public static final long TIMEOUT = 100;
protected static final Log LOGGER = LogFactory.getLog(AbstractParallelBaseTest.class);
static class WebDriverFactory {
static WebDriver create() {
WebDriver driver = null;
try {
LoggingPreferences logs = new LoggingPreferences();
logs.enable(LogType.BROWSER, Level.OFF);
logs.enable(LogType.CLIENT, Level.OFF);
logs.enable(LogType.DRIVER, Level.OFF);
logs.enable(LogType.PERFORMANCE, Level.OFF);
logs.enable(LogType.PROFILER, Level.OFF);
logs.enable(LogType.SERVER, Level.OFF);
DesiredCapabilities desiredCapabilities;
String webDriver = System.getProperty("web.driver");
if ("chrome".equals(webDriver)) {
desiredCapabilities = DesiredCapabilities.chrome();
desiredCapabilities.setCapability(CapabilityType.LOGGING_PREFS, logs);
desiredCapabilities.setCapability(CapabilityType.PROXY, ClientUtil.createSeleniumProxy(proxy));
driver = new ChromeDriver(desiredCapabilities);
} else if ("ie".equals(webDriver)) {
desiredCapabilities = DesiredCapabilities.internetExplorer();
desiredCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
desiredCapabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
desiredCapabilities.setCapability(CapabilityType.LOGGING_PREFS, logs);
desiredCapabilities.setCapability(CapabilityType.PROXY, ClientUtil.createSeleniumProxy(proxy));
driver = new InternetExplorerDriver(desiredCapabilities);
} else if ("firefox".equals(webDriver)) {
desiredCapabilities = DesiredCapabilities.firefox();
desiredCapabilities.setCapability(CapabilityType.LOGGING_PREFS, logs);
driver = new FirefoxDriver(desiredCapabilities);
} else {
desiredCapabilities = DesiredCapabilities.htmlUnitWithJs();
desiredCapabilities.setCapability(CapabilityType.LOGGING_PREFS, logs);
driver = new HtmlUnitDriver(desiredCapabilities);
}
driver.manage().window().setPosition(new Point(0, 0));
driver.manage().window().setSize(new Dimension(1650, 1080));
driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
return driver;
}
}
#Parameterized.Parameter
public int currentDriverIndex;
#Parameterized.Parameters(name = "{0}")
public static ArrayList<Object> driverTypes() {
return Lists.newArrayList(getParams());
}
}
On each implementation of tests I paste #RunWith(ParallelParametrized.class) and it works!
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