How to Handle Alerts Using Headless Browsers (HtmlUnitDriver/Phantomjs Driver) - java

I am using PhantomJs Driver for Headless Testing , I am getting below exception
Sample code:
import static org.testng.Assert.assertEquals;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TestLogin {
WebDriver d;
#BeforeMethod
public void launh_Browser() {
System.setProperty("phantomjs.binary.path", "D:\\Selenium\\driver\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
Capabilities caps = new DesiredCapabilities();
((DesiredCapabilities) caps).setJavascriptEnabled(true);
((DesiredCapabilities) caps).setCapability("takesScreenshot", true);
d=new PhantomJSDriver(caps);
}
#Test
public void guru_banking_login_excel() throws Exception {
d.get("http://www.demo.guru99.com/V4/");
d.findElement(By.name("uid")).sendKeys("TestUser");
d.findElement(By.name("password")).sendKeys("testpwd");
d.findElement(By.name("btnLogin")).click();
try{
Alert alt = d.switchTo().alert();
String actualBoxMsg = alt.getText(); // get content of the Alter Message
assertEquals(actualBoxMsg,"User or Password is not valid");
alt.accept();
}
catch (NoAlertPresentException Ex){
String hometitle=d.getTitle();
assertEquals(hometitle,"Guru99 Bank Manager HomePage");
}
d.quit
}
Error Observed :
Exception : org.openqa.selenium.UnsupportedCommandException: Invalid Command Method - {"headers":{"Accept-Encoding":"gzip,deflate","Cache-Control":"no-cache","Connection":"Keep-Alive","
I am trying to handle popup using phantomjs as a driver
Please help on This .........
Thanks in Advance..!!!!

You have to take care of a lot of points here in your code :
While working with PhantomJS when you mention System.setProperty use the following code lines instead :
File src = new File("C:\\Utility\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
System.setProperty("phantomjs.binary.path", src.getAbsolutePath());
DesiredCapabilities type of objects must be initiated with reference to DesiredCapabilities class only. So change to :
DesiredCapabilities caps = new DesiredCapabilities();
While using assertEquals use Assert.assertEquals as follows :
Assert.assertEquals(actualBoxMsg,"User or Password is not valid");
//
Assert.assertEquals(hometitle,"Guru99 Bank Manager HomePage");
As you are using TestNG, for Assert, use org.testng.Assert; instead of static org.testng.Assert.assertEquals; as an import :
import org.testng.Assert;
You need to wrap up the line d.quit() within a separate TestNG Annotated function too as follows :
#AfterMethod
public void tearDown() {
d.quit();
}
Here is your own code block which executes successfully :
package headlessBrowserTesting;
import java.io.File;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class PhantomJS_webdriver_binary
{
WebDriver d;
#BeforeMethod
public void launh_Browser() {
File src = new File("C:\\Utility\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
System.setProperty("phantomjs.binary.path", src.getAbsolutePath());
DesiredCapabilities caps = new DesiredCapabilities();
((DesiredCapabilities) caps).setJavascriptEnabled(true);
((DesiredCapabilities) caps).setCapability("takesScreenshot", true);
d=new PhantomJSDriver(caps);
}
#Test
public void guru_banking_login_excel() throws Exception {
d.get("http://www.demo.guru99.com/V4/");
d.findElement(By.name("uid")).sendKeys("TestUser");
d.findElement(By.name("password")).sendKeys("testpwd");
d.findElement(By.name("btnLogin")).click();
try{
Alert alt = d.switchTo().alert();
String actualBoxMsg = alt.getText();
Assert.assertEquals(actualBoxMsg,"User or Password is not valid");
alt.accept();
}
catch (NoAlertPresentException Ex){
String hometitle=d.getTitle();
Assert.assertEquals(hometitle,"Guru99 Bank Manager HomePage");
}
}
#AfterMethod
public void tearDown() {
d.quit();
}
}

Related

I have written test cases in java selenium, now I want to run those testcases simantanously

I have created maven project, written some selenium testcases using java, basically I want to login on azure portal & I want to test Resource Group(Name, location & tags). I m using data driven framework. I m taking Test Data & expected data from excel file(.xlsx file), comparing it with Actual value & writing status(pass/fail) & actual data in same excel file. so for that I have written login testcase inside login class & written another testcase which is Resource Group test script inside resource group class, now I want to run both test script which is login & resource group, first the login will run & then resource group test script, resource group test script depends upon login test script.
so anybody can tell how we can do this.
# login test script
package frameworkvalidator;
import FrameworkValidator_Constants.Congig;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.apache.maven.plugins.surefire.report.*;
import frameworkvalidator.TakeScreenshot;
import io.github.bonigarcia.wdm.WebDriverManager;
public class Login {
public WebDriver driver;
#Test
public static void login() throws Exception
{ WebDriverManager.chromedriver().setup();
///System.setProperty("webdriver.chrome.driver",FrameworkValidator_Constants.Congig.chrome_driver_path);
WebDriver driver = new ChromeDriver();
// this.driver= new ChromeDriver();
driver.manage().window().maximize();
// driver.navigate().to(FrameworkValidator_Constants.Congig.baseUrl);
driver.get(FrameworkValidator_Constants.Congig.baseUrl);
try {
Thread.sleep(1000, 500);
driver.findElement(By.id("i0116")).sendKeys(FrameworkValidator_Constants.Congig.username);
Thread.sleep(2000, 1000);
driver.findElement(By.id("idSIButton9")).click();
Thread.sleep(2000, 1000);
driver.findElement(By.id("i0118")).sendKeys(FrameworkValidator_Constants.Congig.password);
Thread.sleep(2000, 1000);
driver.findElement(By.id("idSIButton9")).click();
Thread.sleep(2000, 1000);
driver.findElement(By.id("idSIButton9")).click();
Thread.sleep(2000, 1000);
frameworkvalidator.TakeScreenshot.takeSnapShot(driver,"C:\\sjava\\screenshots\\login.png" );
String actualUrl="https://portal.azure.com/#home";
String expectedUrl= driver.getCurrentUrl();
Assert.assertEquals(expectedUrl,actualUrl);
//driver.close();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Test Resource Group
package Validation;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
//import drivers.DriverManager;
//import drivers.DriverManagerFactory;
//import org.selenium.enums.DriverType;
//import org.selenium.listeners.AnnotationTransformer;
//import org.selenium.listeners.ListenerClass;
//import org.selenium.listeners.MethodInterceptor;
//import org.selenium.reports.ExtentLogger;
//import org.selenium.utils.CookieUtils;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Listeners;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import FrameworkValidator_Constants.Locator_Constants;
import FrameworkValidator_Constants.Congig;
import frameworkvalidator.Xlsx_Reader;
import frameworkvalidator.Login;
public class Test_ResourceGroup {
Xlsx_Reader reader =new Xlsx_Reader(FrameworkValidator_Constants.Congig.Excels_file_path);
String sheetname="RG";
//public static WebDriver driver;
WebDriver driver = new ChromeDriver();
public Test_ResourceGroup(){
}
#org.junit.Test
public void Resource_group_search() throws InterruptedException {
driver.findElement(By.linkText("Resource groups")).click();
Thread.sleep(3000, 1000);
String test_result = reader.getCellData(sheetname,"TEST DATA", 2);
Thread.sleep(4000, 2000);
driver.findElement(By.xpath(FrameworkValidator_Constants.Locator_Constants.RESOURCE_GROUP_SEARCH)).sendKeys(test_result);
Thread.sleep(4000, 2000);
driver.findElement(By.linkText("test_result")).click();
Thread.sleep(4000, 2000);
}
#org.testng.annotations.Test
public void ResourceGroupName() throws Exception{
String resourceGroupNameElement = driver.findElement(By.xpath(FrameworkValidator_Constants.Locator_Constants.RESOURCE_GROUP_NAME_XPATH)).getText();
String expectedResult = reader.getCellData(sheetname,"EXPECTED RESULT",2);
if( resourceGroupNameElement== expectedResult) {
String status= "passed";
}
else {
String status="failed";
}
String status = writer.writeCellData(sheetname,"PASSED/FAILED/SKIP",2);
String actualData = writer.writeCellData(sheetname,"ACTUAL DATA",2);
// Highlighting element & Taking screenshot
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
jsExecutor.executeScript("arguments[0].style.background='yellow'", resourceGroupNameElement);
frameworkvalidator.TakeScreenshot.takeSnapShot(driver,FrameworkValidator_Constants.Congig.Screenshot_folder_path + "T001" );
}
#Test
public void ResourceGroupLocation() throws Exception{
String resourceGroupLocationElement = driver.findElement(By.xpath(FrameworkValidator_Constants.Locator_Constants.RESOURCE_GROUP_LOCATION_XPATH)).getText();
String expectedResult = reader.getCellData(sheetname,"EXPECTED RESULT",3);
if( resourceGroupLocationElement== expectedResult) {
String status= "passed";
}
else {
String status="failed";
}
String status = writer.writeCellData(sheetname,"PASSED/FAILED/SKIP",3);
String actualData = writer.writeCellData(sheetname,"ACTUAL DATA",3);
//Highlighting element & Taking screenshot
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
jsExecutor.executeScript("arguments[0].style.background='yellow'", resourceGroupLocationElement);
frameworkvalidator.TakeScreenshot.takeSnapShot(driver,FrameworkValidator_Constants.Congig.Screenshot_folder_path + "T002" );
}
#Test
public void ResourceGroupTag() throws Exception{
String resourceGroupTagElement = driver.findElement(By.xpath(FrameworkValidator_Constants.Locator_Constants.RESOURCE_GROUP_TAGS_XPATH)).getText();
String expectedResult = reader.getCellData(sheetname,"EXPECTED RESULT",4);
if( resourceGroupTagElement== expectedResult) {
String status= "passed";
}
else {
String status="failed";
}
String status = writer.writeCellData(sheetname,"PASSED/FAILED/SKIP",4);
String actualData = writer.writeCellData(sheetname,"ACTUAL DATA",4);
//Highlighting element & Taking screenshot
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
jsExecutor.executeScript("arguments[0].style.background='yellow'", resourceGroupTagElement);
frameworkvalidator.TakeScreenshot.takeSnapShot(driver,FrameworkValidator_Constants.Congig.Screenshot_folder_path + "T003" );
}
public static void Test_ResourceGroupMain() throws Exception {
Test_ResourceGroup demo= new Test_ResourceGroup();
demo.Resource_group_search();
demo.ResourceGroupName();
demo.ResourceGroupLocation();
demo.ResourceGroupTag();
//Test_ResourceGroup.
//Test_ResourceGroup.ResourceGroupName();
//Test_ResourceGroup.ResourceGroupLocation();
//Test_ResourceGroup.ResourceGroupTag();
//driver.close();
}
}

findElementByAccessibilityid is not shown in eclipse intellisense

I am trying to do a POC for a windows app using winappdriver . I have the winappdriver version 1.1 installed up and running. I want to find the elements by using their automationId. As per winappdriver documentation, elements with AutiomationID can be located by "findElementByAccessibilityId". I am not able to see this locator strategy in my Eclipse intellisense. Instead "findElementsByAccessibilityId" ( notice elements) is been shown up. What should i do so that i can see "findElementByAccessibilityId" locator in intellisense.
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.appium.java_client.windows.WindowsDriver;
public class LoginTest {
private static WindowsDriver<WebElement> driver = null;
#BeforeClass
public static void setup() throws MalformedURLException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("app", "XXXXXXXXXXXXXXXXXXXXXX");
capabilities.setCapability("platformName", "windows");
capabilities.setCapability("deviceName", "windowsPC");
capabilities.setCapability("appWorkingDir", "XXXXXXXXXXXXXXXXXXXXXXXXXX");
driver = new WindowsDriver<WebElement>(new URL("http://127.0.0.1:4723"), capabilities);
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
}
#Test
public void Testing()
{
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.className("TextBox")).sendKeys("XXXX");
driver.findElementById("TxtPwd").sendKeys("XXXX");
driver.findElementsByAccessibilityId("TxtPwd");
driver.findElement(By.id("BtnLogin")).click();
System.out.println("Hi");
}
}
POM.xml

in selenium webdriver while writing code for to take screeshot getting this error

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method copyFile(java.io.File, java.io.File) in the type FileUtils is not applicable for the arguments (java.io.File, com.gargoylesoftware.htmlunit.javascript.host.file.File)
The constructor File(String) is not visible
at DEMO.Screenshot.Homepage(Screenshot.java:37)
at DEMO.Screenshot.main(Screenshot.java:47)
Sample Code:
package DEMO;
import java.io.IOException;
import com.gargoylesoftware.htmlunit.javascript.host.file.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Platform;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.gargoylesoftware.htmlunit.javascript.host.file.File;
public class Screenshot {
WebDriver driver;
public void Homepage() {
System.setProperty("webdriver.gecko.driver", "E:\\selenium_course\\geckodriver.exe");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities = DesiredCapabilities.firefox();
capabilities.setBrowserName("firefox");
capabilities.setVersion("your firefox version");
capabilities.setPlatform(Platform.WINDOWS);
capabilities.setCapability("marionette", false);
driver = new FirefoxDriver(capabilities);
// driver=new ChromeDriver();
driver.get("https://amazon.com");
driver.manage().window().maximize();
// take screen shot and store into variable
java.io.File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// copy screen shot into local system
try {
FileUtils.copyFile(src, new File("E:\\selenium_course\\Screen\\homepage.png"));
} catch (IOException t) {
System.out.println(t.getMessage());
}
driver.close();
}
public static void main(String[] args) {
Screenshot s = new Screenshot();
s.Homepage();
}
}
You use File from com.gargoylesoftware.htmlunit.javascript.host.file, you should use File from java.io. Replace the import
import com.gargoylesoftware.htmlunit.javascript.host.file.File;
With
import java.io.File;
//instead of using try catch at
FILEUTIL.cpy file use that exception handler at public static void main//
public static void main(String[] args) throws exception

"The attribute value is undefined for the annotation type Parameters" error is displayed for Cross-Browser Testing Script

I am trying this cross-browser testing using Selenium.
CrossBrowser.java:
package automationFramewok;
import java.net.MalformedURLException;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.opera.OperaDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.beust.jcommander.Parameters;
// I am getting the following error on the next line
//
// "The attribute value is undefined for the annotation type Parameters"
//
#Parameters({"browser"})
public class CrossBrowser {
#SuppressWarnings("deprecation")
#BeforeTest
public void setUp(String browser) throws MalformedURLException {
if (browser.equalsIgnoreCase("Firefox")) {
System.out.println("Running Firefox");
System.setProperty("webdriver.gecko.driver","E:\\\\Selenium-required files\\geckodriver\\geckodriver.exe");
FirefoxDriver driver = new FirefoxDriver();
} else if (browser.equalsIgnoreCase("chrome")) {
System.out.println("Running Chrome");
System.setProperty("webdriver.chrome.driver", "E:\\\\\\\\Selenium-required files\\\\chromedriver\\\\chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
} else if (browser.equalsIgnoreCase("opera")) {
System.out.println("Running Opera");
// driver = new OperaDriver(); --Use this if the location is set properly--
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("opera.binary", "C://Program Files (x86)//Opera//opera.exe");
capabilities.setCapability("opera.log.level", "CONFIG");
System.setProperty("webdriver.opera.driver", "E:\\\\\\\\Selenium-required files\\\\operadriver\\\\operadriver.exe");
OperaDriver driver = new OperaDriver(capabilities);
}
}
}
I am receiving the following error message:
The attribute value is undefined for the annotation type Parameters
How can I resolve this?
Check out your list of import statements. I think you want
import org.testng.annotations.Parameters;
and not
import com.beust.jcommander.Parameters;
The same issue I was facing and problem was with import statement. I was using the following import statement.
import org.junit.runners.Parameterized.Parameters;
Replaced with the following import statement and issue got resolved.
import org.testng.annotations.Parameters;

How to pass called WebDriver driver from #BeforeMethod to #Test in TestNG Webdriver Java

I have this class SignIn:
package automationFramework;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import pageObject.devSplashScreenPage;
import utility.BrowserType;
import utility.Constant;
import appModule.SignIn_Action;
public class SignIn {
public WebDriver driver;
#BeforeMethod
#Parameters("browser")
public void SetUp(String browser) {
BrowserType.Execute(driver, browser);
}
#Test
public void signIn() {
// Call Sign In function
SignIn_Action.Execute(driver, Constant.StudentUsername, Constant.StudentPassword);
}
#AfterMethod
public void Teardown() {
driver.quit();
}
}
Where I am calling this code below which chooses the specific browser by the parameter that is passed. It works perfectly fine, it picks up the right browser and executes.
package utility;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class BrowserType {
#Test
public static void Execute(WebDriver driver, String browser) {
// Set Browsers
if(browser.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();
}
else if (browser.equalsIgnoreCase("chrome")) {
{System.setProperty("webdriver.chrome.driver","C:/Users/elsid/Desktop/Eclipse/Selenium/chromedriver.exe");}
driver = new ChromeDriver();
}
else if (browser.equalsIgnoreCase("ie")) {
{System.setProperty("webdriver.ie.driver","C:/Users/elsid/Desktop/Eclipse/Selenium/IEDriverServer.exe");}
driver = new InternetExplorerDriver();
{DesiredCapabilities iecapabilities = DesiredCapabilities.internetExplorer();
iecapabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);}
}
// Implicit Wait and Maximize browser
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
// Navigate to URL
driver.get(Constant.URL);
}
}
So everything executes perfectly fine in #BeforeMethod, the issue I have is the test stops because the driver doesn't pass from #BeforeMethod to #Test.
How can I get the driver that is initiated by running BrowserType.class into the #Test Sign_in.class. I guess how can i return the driver properly from browsertype and call it in Sign_in #Test.
Thanks
You should make your Execute function return the driver:
public static WebDriver Execute(String browser) {
...
return driver;
}
In your test:
public void SetUp(String browser) {
driver = BrowserType.Execute(browser);
}
Solved like this:
BrowserType.java:
package utility;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class BrowserType {
#Test
public static WebDriver Execute(String browser) {
// Set Browsers
WebDriver driver = null;
if(browser.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();
}
else if (browser.equalsIgnoreCase("chrome")) {
{System.setProperty("webdriver.chrome.driver","C:/Users/elsid/Desktop/Eclipse/Selenium/chromedriver.exe");}
driver = new ChromeDriver();
}
else if (browser.equalsIgnoreCase("ie")) {
{System.setProperty("webdriver.ie.driver","C:/Users/elsid/Desktop/Eclipse/Selenium/IEDriverServer.exe");}
driver = new InternetExplorerDriver();
{DesiredCapabilities iecapabilities = DesiredCapabilities.internetExplorer();
iecapabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);}
}
// Implicit Wait and Maximize browser
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
// Navigate to URL
driver.get(Constant.URL);
return driver;
}
SignIn.java class:
package automationFramework;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import pageObject.devSplashScreenPage;
import utility.BrowserType;
import utility.Constant;
import appModule.SignIn_Action;
public class SignIn {
public WebDriver driver;
#BeforeMethod
#Parameters("browser")
public void SetUp(String browser) {
driver = BrowserType.Execute(browser);
}
#Test
public void signIn() {
// Call Sign In function
SignIn_Action.Execute(driver, Constant.StudentUsername, Constant.StudentPassword);
}
#AfterMethod
public void Teardown() {
driver.quit();
}
}
The way your doing things can be greatly improved.
public class BrowserTest extends TestBase{
#Test(dataProvider="test1")
public static void execute(WebDriverHelper helper, String browser) {
// Set Browsers
driver.get(url);
Just pass the driver object (coming from the DataProvider). I assume your generating the driver instance within the DataProvider method since your test method is already parameterized and takes the driver.
public class TestBase {
private WebDriver driver;
...
#BeforeMethod
#Parameters("browser")
public void setUp(Object[] params) {
driver = (WebDriverHelper)params.get(1);
browserName = (String)params.get(2);
this.setTestName( params.get(0) + "-" + browserName;
driver.navigateTo(startUrl);
}
This code I show above wont compile but what I am trying to convey here is that you need to use the optional TestNG arg to the #BeforeMethod method, which is Object[] , and it gives you access to objects passed to test methods, BEFORE the test method is called, such as getting access to a "driver helper" created in the DataProvider factory, and then doing some Capabilities setup on that before the test is ran.
#DataProvider(name = "test1")
public Object[][] createData1() {
return new Object[][] {
{ "Cedric", new WebDriverHelper(), "firefox" },
{ "Anne", new WebDriverHelper(), "chrome"}
};
}
public class TestSuiteDriver {
private static WebDriver driver;
#BeforeClass
public static void setUp(){
System.setProperty("webdriver.chrome.driver", "/Users/Kimberleyross/chromedriver");
driver = new ChromeDriver();
}
public static WebDriver getDriver() {
return TestSuiteDriver.driver;
}
}

Categories

Resources