am trying to follow along with a time sensitive selenium course and I am just getting hopelessly lost. I was only able to execute this test the first time using chrome and not firefox but then i started getting errors connecting to chrome and went back to firefox. Below is the script from the tutorial course which SHOULD work. I have added the path to firefox.exe in my system variables and I am running firefox 47 which I downgraded to see if that would help. I'm using JDK 1.8 and selenium 3.6.0. Here is the code from the course. My eclipse is borking at the line driver = new FirefoxDriver(ffBinary, firefoxProfile); the red underline asks to "remove this argument to match firefoxDriver".
If I remove it according to the instructions as just have driver = new Firefox Driver, I then get this error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at Guru99package.TestScript02.main(TestScript02.java:72)
Line 72 is the starting line for the whole main function, so this is really unclear for me. As far as I can tell, the reason it won't compile could be anything and the syntax for firefox path matches what I'm seeing in github tutorials and google.
I tried doing this in chrome and can paste my results here, but I also got really confused in chrome as to whether I was supposed to instantiate my webdriver using webdriver or RemoteWebDriver. When I called Chrome like this:
System.setProperty("webdriver.chrome.driver", "C:\\selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
my script initially ran but wouldn't input anything in the login fields. Now it seems that nothing I do is working. The tutorial doesn't have a forum or help options.
Code for the main file:
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
public class TestScript02 {
static WebDriver driver; // Selenium control driver
private static String baseUrl; // baseUrl of Website Guru99
// This method SetUp will read initialization parameters from the classUtil.java & launch Firefox
public static void setUp() throws Exception {
/*
* Tells the Selenium client library to connect to the Webdriver
* service using firefox
*
* In some PC's, Selenium can not find the binary file of Firefox because
* user doesn't install Firefox at its default location. We need to tell
* Selenium where the firefox.exe is
*/
File pathToBinary = new File(Util.FIREFOX_PATH);
FirefoxBinary ffBinary = new FirefoxBinary(pathToBinary);
/*
* Create new firefoxProfile for Testing
*
* A profile in Firefox is a collection of bookmarks, browser settings,
* extensions, passwords, and history; in short, all of your personal
* settings. Firefox uses a DEFAULT profile to store all of your
* personal settings.
*
* In this case, we use Firefox for "testing" purpose not as an "end user".
* We need to create NEW firefoxProfile because we want to separate the
* Firefox profile for testing purpose and that of an end user. If
* something wrong happens with the testing, you still have your DEFAULT
* profile to fall back to (your personal data still safe).
*/
FirefoxProfile firefoxProfile = new FirefoxProfile();
driver = new FirefoxDriver(ffBinary, firefoxProfile);
// Setting Base URL of website Guru99
baseUrl = Util.BASE_URL;
// Specifies the amount of time the driver should wait when searching for an element if it is not immediately present.
// Refer - http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/WebDriver.Timeouts.html
driver.manage().timeouts()
.implicitlyWait(Util.WAIT_TIME, TimeUnit.SECONDS);
// Go to http://www.demo.guru99.com/V4/
driver.get(baseUrl + "/V4/");
}
/**
*
* #author Krishna Rungta
* Test Script 02
* **************
* This method will perform following Test Steps
*
* 1) Go to http://www.demo.guru99.com/V4/
2) Enter valid UserId
3) Enter valid Password
4) Click Login
5) Verify the Page Title after login
*/
public static void main(String[] args) throws Exception {
String username, password;
String actualTitle;
String actualBoxtitle;
//Setup Firefox driver
setUp();
driver.findElement(By.name("uid")).clear(); // Good practice to clear a field before use
driver.findElement(By.name("uid")).sendKeys(Util.USER_NAME); // Enter username
driver.findElement(By.name("password")).clear(); // Good practice to clear a field before use
driver.findElement(By.name("password")).sendKeys(Util.PASSWD); // Enter Password
// Click Login
driver.findElement(By.name("btnLogin")).click();
actualTitle = driver.getTitle();
if (actualTitle.contains(Util.EXPECT_TITLE)) {
System.out.println("Test case: Passed");
}
else {
System.out.println("Test case : Failed");
}
driver.close();
}
}
Code for util.java:
package Guru99package;
public class Util {
/* You can change the Path of FireFox based on your environment here */
public static final String FIREFOX_PATH = "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe";
// Setting Base URL
public static final String BASE_URL = "http://www.demo.guru99.com/";
// Time to wait when searching for a GUI element
public static final int WAIT_TIME = 30;
// Valid account for login
public static final String USER_NAME = "mngr103067";
public static final String PASSWD = "pepysYd";
// Expected output
public static final String EXPECT_TITLE = "Guru99 Bank Manager HomePage";
}
Related
I am implementing my code to work on remote machines on Sauce Labs. The code worked fine until I have changed my driver initialisation (to work with remote server). I keep getting this.driver is null exception. I don't know what's wrong with it, I was following official documentation and tried many things. I hope someone can see the issue here. Thank you in advance. My code:
DRIVER:(my username and key are copied from my sauce labs account, renamed for this purpose)
public class Hooks {
public RemoteWebDriver driver;
public WebDriverWait wait;
#Before
public void setup(Scenario scenario) throws MalformedURLException {
String username = System.getenv("my username");
String accessKey = System.getenv("key");
ChromeOptions chromeOpts = new ChromeOptions();
MutableCapabilities sauceOpts = new MutableCapabilities();
sauceOpts.setCapability("name", scenario.getName());
sauceOpts.setCapability("username", username);
sauceOpts.setCapability("accessKey",accessKey);
MutableCapabilities browserOptions = new MutableCapabilities();
browserOptions.setCapability(ChromeOptions.CAPABILITY, chromeOpts);
browserOptions.setCapability("sauce:options", sauceOpts);
browserOptions.setCapability("browserName", "chrome");
browserOptions.setCapability("browserVersion", "latest");
browserOptions.setCapability("platformName", "Windows 10");
String sauceUrl = "https://ondemand.us-west-1.saucelabs.com:443/wd/hub";
URL url = new URL(sauceUrl);
driver = new RemoteWebDriver(url, browserOptions);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
#After
public void tearDown(Scenario scenario) {driver.quit();}
}
PAGE OBJECT WHERE MY CODE IS: (shortened for privacy purposes)
public class LandingPO extends Hooks {
static RemoteWebDriver driver;
static WebDriverWait wait;
String url = "https://google.com"
public void openUrl() {
driver.get(url);}
And then I just call this method (landingPO.openUrl();) in my stepDefinition class.
The error is thrown where first driver usage is found:
Step failed
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.remote.RemoteWebDriver.get(String)" because "pageObjects.LandingPO.driver" is null
it breaks right at "driver.get(url)" in my LandingPO
If anyone will have the same problem, the answer was:
I was using wrong Before/After import. The correct import should be:
import io.cucumber.java.After;
import io.cucumber.java.Before;
I am very new to selenium UI automation and I am trying my hands on with a simple application. I am using java with testNG. I need to integrate this test with CI and the test environment url will be different with every deployment. I am passing this as a parameter, difference between test and prod environment is that in the test, there won't be any login screen hence there is no need for authentication but my test verifies login and a login method. I need to be able to skip this test based on the URL supplied. Here is my code and the problem is testNG always suggests that the test was skipped but I can see it executing the login method. Please help me correct or understand what mistake I am committing.
public class Login {
WebDriver driver;
//Parameter - test environment URL
String url = System.getProperty("environment");
#Test (priority = 1)
public void verifyLogin() {
//Skip verifyLogin test in non prod environments
System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
if (url=="www.google.com")
//If url matches production url then execute the test, if url doesn't match production URL then skip login test as there won't be any authentication/login in non prod
{
LoginPage login = new LoginPage(driver);
login.signIn();
Assert.assertEquals(driver.getTitle(), "Application Name", "Login failed,");
String title = driver.getTitle();
System.out.println("Page title is " + title);
driver.close();
}
else if (url!="www.google.com"){
throw new SkipException("Skipping this test");
}
}
#Test(priority = 2)
public void userKey() {
System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
//If URL equals prod then call the login method to be able to login to the app else just execute the userKey method without having the need to login
if (url=="www.google.com");
{
LoginPage login = new LoginPage(driver);
login.signIn();
}
AccountManagementPage userKey = new AccountManagementPage(driver);
userKey.key();
driver.close();
}
}
The very exact use case is well explained here without throwing SkipException.
The idea is to create a custom annotation for the methods to be skipped & read the methods using IMethodInterceptor - decide to execute or not behind the scenes.
Updated for the question in the comment section:
You do not have to worry about 'TestEnvironment' or 'TestParameters' class.Just directly use the production check logic here.
Predicate<IMethodInstance> isTestExecutingOnProduction = (tip) -> {
return system.getProperty("env").
.equals("<production check here>");
};
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class sasas {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver","D:\\Firefox\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
String appUrl = "https://accounts.google.com";
driver.manage().window().maximize();
driver.get(appUrl);
System.out.println("Test script executed successfully.");
driver.close();
}
}
this is the sample code i am trying. when i run i get the error message as "The driver executable does not exist: D:\Firefox\geckodriver.exe" please help me to proceed. i added the location in environmental variable then too i get this error . PATH i added as D:\Samplecode.
kindly help me
(1) To use gecko driver, make sure you are using Firefox version 55 and above to get better gecko Web-Driver feature support, find out more here
(2) Perhaps, you should downgrade Selenium to a lower version i.e. version 2.53.1. Selenium version 2.53.1 runs perfectly on Firefox 47.0.1 and lower, does not require using web driver API. I have ran your code against this and it worked fine.
public class Sasas {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
String appUrl = "https://accounts.google.com";
driver.manage().window().maximize();
driver.get(appUrl);
System.out.println("Test script executed successfully.");
driver.close();
}
}
Use the relative path:
JAVA
1.- In your project, create the Drivers/Win/Firefox/geckodriver.exe folder and add your .exe
2.- Replace:
System.setProperty("webdriver.gecko.driver","D:\\Firefox\\geckodriver.exe");
For:
String path = System.getProperty("user.dir") + "/Drivers/Win/Firefox/Geckodriver.exe";
System.setProperty("webdriver.gecko.driver", path);
Note: using the relative path is the most optimal
My code:
package pak0310;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class class0310
{
public static void main(String[] args)
{
// objects and variables instantiation
WebDriver driver = new FirefoxDriver();
String appUrl = "https://accounts.google.com";
// launch the firefox browser and open the application url
driver.get(appUrl);
// maximize the browser window
driver.manage().window().maximize();
// declare and initialize the variable to store the expected title of the webpage.
String expectedTitle = " Sign in - Google Accounts ";
// fetch the title of the web page and save it into a string variable
String actualTitle = driver.getTitle();
// compare the expected title of the page with the actual title of the page and print the result
if (expectedTitle.equals(actualTitle))
{
System.out.println("Verification Successful - The correct title is displayed on the web page.");
}
else
{
System.out.println("Verification Failed - An incorrect title is displayed on the web page.");
}
// enter a valid username in the email textbox
WebElement username = driver.findElement(By.id("Email"));
username.clear();
username.sendKeys("TestSelenium");
// enter a valid password in the password textbox
WebElement password = driver.findElement(By.id("Passwd"));
password.clear();
password.sendKeys("password123");
WebElement SignInButton = driver.findElement(By.id("signIn"));
SignInButton.click();
// close the web browser
driver.close();
System.out.println("Test script executed successfully.");
// terminate the program
System.exit(0);
}
}
Error:
Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see https://github.com/mozilla/geckodriver. The latest version can be downloaded from https://github.com/mozilla/geckodriver/releases
at com.google.common.base.Preconditions.checkState(Preconditions.java:754)
at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:124)
at org.openqa.selenium.firefox.GeckoDriverService.access$100(GeckoDriverService.java:41)
at org.openqa.selenium.firefox.GeckoDriverService$Builder.findDefaultExecutable(GeckoDriverService.java:115)
at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:329)
at org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:207)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:103)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:99)
at pak0310.class0310.main(class0310.java:22)
...
In this similar question (https://stackoverflow.com/a/38752315/8195985) user Paras answered:
You are using latest version of Selenium WebDriver i.e. Selenium 3.x, this version of webdriver doesn't support direct firefox launch. You have to set the SystemProperty for webdriver.gecko.driver.
Replace the Code:-
WebDriver driver; =new FirefoxDriver();
With This code:-
WebDriver driver;
System.setProperty("webdriver.gecko.driver", "<Path to your WebDriver>");
driver =new FirefoxDriver();
Maybe use that will help you.
Download geckodriver from https://github.com/mozilla/geckodriver/releases
unzip folder you will get like this geckodriver.exe
Copy that paste in some where and copy the complete path with driver.
use below code in <path> place paste your path
System.setProperty("webdriver.gecko.driver", "your path");
WebDriver driver = new FirefoxDriver();
This error suggesting to use of geckodriver (post Selenium 3), to launch Firefox. You can refer
How to use the gecko executable with Selenium
I am working on frame based website. I am using selenium 2.47.1 & PhantomJS 1.9.2. I have written Automation Script & run it using firefox driver, it works perfectly. I am trying to execute the code with help PhanthomJS driver. But whenever I am trying to execute the it gives NoSuchFrameFoundException. My script is given below...
public class iFrame {
public String baseUrl = "https://test5.icoreemr.com/interface/login/login.php";
public WebDriver cd;
String scenarioName = "Sheet1";
ExcelLibrary ex = new ExcelLibrary();
#BeforeTest
public void SetBaseUrl() {
Capabilities caps = new DesiredCapabilities();
((DesiredCapabilities) caps).setJavascriptEnabled(true);
((DesiredCapabilities) caps).setCapability(
PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
"C:\\Users\\Probe7\\Downloads\\phantomjs-1.9.2-windows\\phantomjs.exe"
);
this.cd = new PhantomJSDriver(caps);
cd.get(baseUrl);
cd.manage().window().maximize();
}
#Test(priority = 0)
/* Login into the Application */
public void Login() {
cd.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);
cd.switchTo().frame("Login");
System.out.println("Control Moved to Login Frame");
String UserName = ex.getExcelValue(scenarioName, 2, 4);
cd.findElement(By.xpath("//body/center/form/table/tbody/tr/td/div/div[2]/table/tbody/tr[1]/td[2]/input")).sendKeys(UserName);
}
Above code gives following exception..
org.openqa.selenium.NoSuchFrameException: No frame element found by name or id Login
Eventhough same script works perfectly in firefox driver, but not in PhantomJS.
Please advice me what went wrong?? I am looking into this nearly a day, but didn't find any solution.. Please help me on this?
Thanks in Advance...