I am writing automatic tests using Java with Selenium Grid and JUnit framework and I have encountered a problem with user input. So my code looks like this:
package com.example.tests;
import com.thoughtworks.selenium.DefaultSelenium;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Scanner;
import static org.junit.Assert.fail;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class test {
private DefaultSelenium selenium;
#Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 5555, "*googlechrome", "www.google.com");
selenium.start();
}
#Test
public void Test() throws Exception {
// some tests here
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
I would like to add a user input, so when user types for example "Google Chrome", the test will start with Google Chrome, when he types "Firefox", the test will start with Firefox etc. I have tried to put
Scanner in = new Scanner(System.in);
String web_browser = in.next();
somwhere in my code (in setUp method for example), but when the program starts, I can't type anything in the console. Does anyone know the solution for this?
It's tricky dealing with System.in in the test.
I suggest that you rather read your driver preference as a system property?
String driver = System.getProperty("driver");
if (driver != null) {
//use that driver
}
else {
//use default driver
}
You can the launch your test like
mvn test -Ddriver=chrome
or by setting them in your IDE
Related
Given below is the code that I coded using selenium in eclipse.
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
class GoogleSearchTest {
#Test
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver","C:\\Users\\acer\\Downloads\\selenium\\geckodriver.exe");
WebDriver driver =new FirefoxDriver();
driver.get("https://www.google.com/");
WebElement we1 = driver.findElement(By.name("q"));
we1.sendKeys("GMAIL");
we1.sendKeys(Keys.ENTER);
WebDriverWait wait1 = new WebDriverWait(driver, 5);
wait1.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h3[text()='E-mail - Sign in - Google Accounts']"))).click();
Thread.sleep(10000);
driver.findElement(By.id("identifierId")).sendKeys("2017cs102#stu.ucsc.cmb.ac.lk");
driver.findElement(By.xpath("//*[#id='identifierNext']/div/span/span")).click();
Thread.sleep(10000);
driver.findElement(By.name("password")).sendKeys("mmalsha425#gmail.com");
driver.findElement(By.xpath("//*[#id='passwordNext']/div/span/span")).click();
}
}
It gives the following error.
[TestNG] No tests found. Nothing was run
Usage: <main class> [options] The XML suite files to run
I have already installed TestNG plugin.What can I do to fix this problem??
Change the main function name. You should not use it while using TestNG
#Test
public void test() throws InterruptedException {
System.setProperty("webdriver.gecko.driver","C:\\Users\\acer\\Downloads\\selenium\\geckodriver.exe");
WebDriver driver =new FirefoxDriver();
You don't need to write main() method, TestNg do that by itself.
class GoogleSearchTest {
#Test
public void test() throws InterruptedException{
//your code here
.....
}
}
If you want to call from main(), simply:
import org.testng.TestNG;
public class Master {
public static void main(String[] args) {
TestNG testng = new TestNG();
testng.setTestClasses(new Class[] { GoogleSearchTest.class });
testng.run();
}
}
But note, in GoogleSearchTest class don't put public static void main for #Test
This error message...
[TestNG] No tests found. Nothing was run
Usage: <main class> [options] The XML suite files to run
...implies that the TestNG found no tests hence nothing was executed.
TestNG
TestNG is an annotation-based test framework which needs a marker annotation type to indicate that a method is a test method, and should be run by the testing tool. Hence, while using testng as you use annotations and you don't have to call the main() method explicitly.
Solution
The simple solution would be to replace the main() method with a test method name e.g. test() and keep the #Test annotation as follows:
// your imports
class GoogleSearchTest {
#Test
public void test() throws InterruptedException {
System.setProperty("webdriver.gecko.driver","C:\\Users\\acer\\Downloads\\selenium\\geckodriver.exe");
// other lines of code
}
}
I'm new with cucumber and learned this doc carefully to understand how could I implement my first cucumber java project. I have done a lot of analysis and gone through almost all the articles related to it over internet, why its not picking up step definition but could not find the cause. However, everything seems to be OK as per my understanding, I have great expectation that you guys can find my fault at one go.
Looking forward for a +ve response.
Hence I'm sharing the code, message(on console window) and folder structure.
Thanks
Rafi
Feature file:
#MyApplication
Feature: Post text Hello Rafi on Rafi facebook account
Scenario: Login successfully on Facebook application
Given Open Facebook application
When Enter valid id and password
And Click on Login button
Then Facebook home page should open
TestRunner class:
package test.java.runner;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
//glue = {"helpers", "src.test.java.steps"},
#RunWith(Cucumber.class)
#CucumberOptions(
features = {"src/features"},
glue = {"helpers", "src.test.java.steps"},
plugin = {"pretty","html:target/cucumber-html-report"},
dryRun = true,
monochrome = true,
tags="#MyApplication",
strict=false)
public class TestRunner {
}
StepDefinition class:
package test.java.steps;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import cucumber.api.PendingException;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class StepDefinition {
private static WebDriver driver = null ;
private static String password = "*********";
WebDriverWait wait=new WebDriverWait(driver, 30);
WebElement waitElement;
#BeforeClass
public void setup() throws Throwable
{
System.setProperty("webdriver.gecko.driver", "C:\\Selenium Automation\\selenium\\Selenium 3 and Firefox Geckodriver\\geckodriver.exe");
driver = new FirefoxDriver ();
driver.manage().window().maximize();
}
#AfterClass
public void teardown() throws Throwable
{driver.quit();}
// First scenario
#Given("^Open Facebook application$")
public void open_Facebook_application() throws Throwable{
System.out.println("this is not working");
driver.navigate().to("https://www.facebook.com/");
}
#When("^Enter valid id and password$")
public void enter_valid_id_and_password() throws Throwable{
driver.findElement(By.name("email")).clear();
driver.findElement(By.name("email")).sendKeys("rafiras16#gmail.com");
driver.findElement(By.name("pass")).clear();
driver.findElement(By.name("pass")).sendKeys(password);
}
#When("^Click on Login button$")
public void click_on_Login_button() throws Throwable {
driver.findElement(By.xpath("//input[starts-with(#id,'u_0')]")).click();
}
#Then("^Facebook home page should open$")
public void facebook_home_page_should_open() throws Throwable{
String strTitle = driver.getTitle();
System.out.print(strTitle);
}
}
image for message on console window and folder structure
BuildPath details
I think the glue attribute on the CucumberOptions class is wrong. If you want to refer to the step definitions using the file path then you need to change that to:
glue = {"helpers", "src/test/java/steps"},
If you want to refer them by package then you need to remove the "src." prefix:
glue = {"helpers", "test.java.steps"},
Try changing,
glue = {"helpers", "src.test.java.steps"}
to
glue = {"test.java.steps"}
And what is this helpers package i don't see it in the screenshot.
The #AfterClass and #BeforeClass annotations are useful only if the class is a junit test class. You have placed them in a normal class, thus they will not be run. This leads to the driver remaining uninitaialized.
The easy way out is to use the cucumber #Before and #After annotation. Change the #BeforeClass to #Before and #AfterClass to #After.
im working with Selenum, after exporting the test to Junit 4 RC, Im facing compilation error.
the selenium.sendKeys is undefined
(The method sendKeys(String, String) is undefined for the type Selenium)
My environment is Eclipse and the Selenium jars are updated from vertion 3.3 to 3.5
attached code:
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
public class loginGustCOP_NET {
private Selenium selenium;
#Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://shaula01:7001/");
selenium.start();
}
#Test
public void test() throws Exception {
selenium.sendKeys("id=categoryId", "0000");
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}
What can be done?
I suppose you mean version 2.35. You need to use type(String locator, String text) method in order to write text to some input. sendText method is only available in Selenium WebDriver.
Basically every time I run my java code from eclipse, webdriver launches a new ie browser and executes my tests successfully for the most part. However, I have a lot of tests to run, and it's a pain that webdriver starts up a new browser session every time. I need a way to re-use a previously opened browser; so webdriver would open ie the first time, then the second time, i run my eclipse program, I want it to simply pick up the previous browser instance and continue to run my tests on that same instance. That way, I am NOT starting up a new browser session every time I run my program.
Say you have 100 tests to run in eclipse, you hit that run button and they all run, then at about the 87th test you get an error. You then go back to eclipse, fix that error, but then you have to re-run all 100 test again from scratch.
It would be nice to fix the error on that 87th test and then resume the execution from that 87th test as opposed to re-executing all tests from scratch, i.e from test 0 all the way to 100.
Hopefully, I am clear enough to get some help from you guys, thanks btw.
Here's my attempt below at trying to maintain and re-use a webdriver internet explorer browser instance:
public class demo extends RemoteWebDriver {
public static WebDriver driver;
public Selenium selenium;
public WebDriverWait wait;
public String propertyFile;
String getSessionId;
public demo() { // constructor
DesiredCapabilities ieCapabilities = DesiredCapabilities
.internetExplorer();
ieCapabilities
.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true);
driver = new InternetExplorerDriver(ieCapabilities);
this.saveSessionIdToSomeStorage(getSessionId);
this.startSession(ieCapabilities);
driver.manage().window().maximize();
}
#Override
protected void startSession(Capabilities desiredCapabilities) {
String sid = getPreviousSessionIdFromSomeStorage();
if (sid != null) {
setSessionId(sid);
try {
getCurrentUrl();
} catch (WebDriverException e) {
// session is not valid
sid = null;
}
}
if (sid == null) {
super.startSession(desiredCapabilities);
saveSessionIdToSomeStorage(getSessionId().toString());
}
}
private void saveSessionIdToSomeStorage(String session) {
session=((RemoteWebDriver) driver).getSessionId().toString();
}
private String getPreviousSessionIdFromSomeStorage() {
return getSessionId;
}
}
My hope here was that by overriding the startSession() method from remoteWebdriver, it would somehow check that I already had an instance of webdriver browser opened in i.e and it would instead use that instance as opposed to re-creating a new instance everytime I hit that "run" button in eclipse.
I can also see that because I am creating a "new driver instance" from my constructor, since constructor always execute first, it creates that new driver instance automatically, so I might need to alter that somehow, but don't know how.
I am a newbie on both stackoverflow and with selenium webdriver and hope someone here can help.
Thanks!
To answer your question:
No. You can't use a browser that is currently running on your computer. You can use the same browser for the different tests, however, as long as it is on the same execution.
However, it sounds like your real problem is running 100 tests over and over again. I would recommend using a testing framework (like TestNG or JUnit). With these, you can specify which tests you want to run (TestNG will generate an XML file of all of the tests that fail, so when you run it, it will only execute the failed tests).
Actually you can re-use the same session again..
In node client you can use following code to attach to existing selenium session
var browser = wd.remote('http://localhost:4444/wd/hub');
browser.attach('df606fdd-f4b7-4651-aaba-fe37a39c86e3', function(err, capabilities) {
// The 'capabilities' object as returned by sessionCapabilities
if (err) { /* that session doesn't exist */ }
else {
browser.elementByCss("button.groovy-button", function(err, el) {
...
});
}
});
...
browser.detach();
To get selenium session id,
driver.getSessionId();
Note:
This is available in Node Client only..
To do the same thing in JAVA or C#, you have to override execute method of selenium to capture the sessionId and save it in local file and read it again to attach with existing selenium session
I have tried the below steps to use the same browser instance and it worked for me:
If you are having generic or Class 1 in different package the below code snippet will work -
package zgenerics;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebDriver;
// Class 1 :
public class Generics {
public Generics(){}
protected WebDriver driver;
#BeforeTest
public void maxmen() throws InterruptedException, IOException{
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String appURL= "url";
driver.get(appURL);
String expectedTitle = "Title";
String actualTitle= driver.getTitle();
if(actualTitle.equals(expectedTitle)){
System.out.println("Verification passed");
}
else {
System.out.println("Verification failed");
} }
// Class 2 :
package automationScripts;
import org.openqa.selenium.By;
import org.testng.annotations.*;
import zgenerics.Generics;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class Login extends Generics {
#Test
public void Login() throws InterruptedException, Exception {
WebDriverWait wait = new WebDriverWait(driver,25);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("")));
driver.findElement(By.cssSelector("")).sendKeys("");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("")));
driver.findElement(By.xpath("")).sendKeys("");
}
}
If your Generics class is in the same package you just need to make below change in your code:
public class Generics {
public Generics(){}
WebDriver driver; }
Just remove the protected word from Webdriver code line. Rest code of class 1 remain as it is.
Regards,
Mohit Baluja
I have tried it by extension of classes(Java Inheritance) and creating an xml file. I hope below examples will help:
Class 1 :
package zgenerics;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebDriver;
public class SetUp {
public Generics(){}
protected WebDriver driver;
#BeforeTest
public void maxmen() throws InterruptedException, IOException{
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String appURL= "URL";
driver.get(appURL);
String expectedTitle = "Title";
String actualTitle= driver.getTitle();
if(actualTitle.equals(expectedTitle)){
System.out.println("Verification passed");
}
else {
System.out.println("Verification failed");
} }
Class 2 :
package automationScripts;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
import zgenerics.SetUp
public class Conditions extends SetUp {
#Test
public void visible() throws InterruptedException{
Thread.sleep(5000);
boolean signINbutton=driver.findElement(By.xpath("xpath")).isEnabled();
System.out.println(signINbutton);
boolean SIGNTEXT=driver.findElement(By.xpath("xpath")).isDisplayed();
System.out.println(SIGNTEXT);
if (signINbutton==true && SIGNTEXT==true){
System.out.println("Text and button is present");
}
else{
System.out.println("Nothing is visible");
}
}
}
Class 3:
package automationScripts;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Test;
public class Footer extends Conditions {
#Test
public void footerNew () throws InterruptedException{
WebElement aboutUs = driver.findElement(By.cssSelector("CssSelector"));
aboutUs.click();
WebElement cancel = driver.findElement(By.xpath("xpath"));
cancel.click();
Thread.sleep(1000);
WebElement TermsNCond = driver.findElement(By.xpath("xpath"));
TermsNCond.click();
}
}
Now Create an xml file with below code for example and run the testng.xml as testng suite:
copy and paste below code and edit it accordingly.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestSuite" parallel="classes" thread-count="3">
<test name="PackTest">
<classes>
<class name="automationScripts.Footer"/>
</classes>
This will run above three classes. That means one browser and different tests.
We can set the execution sequence by setting the class names in alphabetical order as i have done in above classes.
I am trying to login to our company product site via selenium.I am able to do it via the Selenium IDE. And this is the code that the IDE exports using JUnit4(Remote Control):
package com.beginning;
import com.thoughtworks.selenium.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.regex.Pattern;
public class testcase extends SeleneseTestCase {
#Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "link");
selenium.start();
}
#Test
public void testTestcase() throws Exception {
selenium.open("complete link");
selenium.type("name=j_username", "username");
selenium.type("name=j_password", "password");
selenium.click("css=input[type=\"submit\"]");
selenium.waitForPageToLoad("30000");
//selenium.click("link=Sign out");
//selenium.waitForPageToLoad("30000");
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}
My doubts are :
1.Why does selenium IDE export the browser type as *chrome when I am actually doing it in firefox.
2.If I use the test as it is, it enters the values and then gives an exception .
3.If I change the browser Type to *firefox, it starts execution but nothing happens at all. Basically hangs.
Things work fine when doing it from the IDE.
Thanks.
Change your "link" (4th parameter of DefaultSelenium constructor) so it's actually a valid URL (the site you want to target)
Would reccommend you to check the version of firefox and upgrade to latest.I have used a similar scenario. Pls find the code below.
You can use this its works grt.Hope you find it useful.
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
public class TestRun {
public static void main(String[] args)
{
Selenium selenium=new DefaultSelenium("localhost", 4444 , "*firefox","myurl");
selenium.start();
selenium.open("myurl");
System.out.println("Open browser "+selenium);
selenium.windowMaximize();
selenium.type("id=j_username","Lal");
selenium.type("name=j_password","lal");
selenium.click("name=submit");
**selenium.waitForPageToLoad("60000");**
if(selenium.isTextPresent("Lal"))
{
selenium.click("id=common_header_logout");
}
else
{
System.out.println("User not found");
}
}
}