Is it possible to make Selenium WebDriver executable file in java?
I have written code in java for data driven testing using Selenium WebDriver. I want to make it executable file so that outside eclipse one can execute it.
package pkg;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class LogingS {
private WebDriver driver;
private String baseUrl;
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.example.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testLogingS() throws Exception {
driver.get(baseUrl);
System.out.println("The current Url: " + driver.getCurrentUrl());
driver.findElement(By.id("id_email")).clear();
driver.findElement(By.id("id_email")).sendKeys("com");
Thread.sleep(1000);
driver.findElement(By.id("id_password")).clear();
driver.findElement(By.id("id_password")).sendKeys("123");
Thread.sleep(1000);
System.out.println("The current Url: " + driver.getCurrentUrl());
driver.findElement(By.id("btn_login")).submit();
Thread.sleep(5000);
System.out.println("The current Url: " + driver.getCurrentUrl());
}
#After
public void tearDown() throws Exception {
}
}
To create a new JAR file in the workbench:
Either from the context menu or from the menu bar's File menu, select Export.
Expand the Java node and select JAR file. Click Next.
In the JAR File Specification page, select the resources that you want to export in the Select the resources to export field.
In the Select the export destination field, either type or click Browse to select a location for the JAR file and Finish
Open CMD, move upto your .jar
Call jar file using following command :-
java -jar xxx.jar
Have you tried using ant script to run your test cases, I assume you have written your test case using Junit.
Thanks!
I would suggest you to create a runnable jar of your selenium test project so that you will be able to execute it outside Eclipse IDE.
These links will help you:
Make executable jar file of webdriver project
Create runnable jar file for selenium project blog post
Making jar file of a test project in selenium webdriver
If you are test cases using jUnits then it is very simple to execute them in Eclipse. But before that you need to execute the core Selenium classes which will come to your help very frequently.
org.openqa.selenium.WebDriver: The main interface to use for testing, which represents an idealised web browser. The methods in this class fall into three categories – Control of the browser itself, Selection of WebElements, Debugging aids
org.openqa.selenium.WebElement: Represents an HTML element. Generally, all interesting operations to do with interacting with a page will be performed through this interface.
org.openqa.selenium.By: Mechanism used to locate elements within a document.
Below is a sample class which illustrates a Selenium test case.
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class TestEndToEndPages {
private WebDriver driver;
#Before
public void setUp() {
// Create a new instance of the html unit driver
driver = new HtmlUnitDriver();
//Navigate to desired web page
driver.get("http://localhost:6060/WebApplication4Selenium");
}
#Test
public void shouldBeAbleEnterUserNameAndClickSubmitToVerifyWelcomeMessage()
{
// verify title of index page
verifyTitle("Enter your name");
//verify header of index page
verifyHeaderMessage("Please enter your name");
//enter user name as Allen
enterUserName("Allen");
//verify title of welcome page
verifyTitle("Welcome");
//verify header of welcome page
verifyHeaderMessage("Welcome Allen!!!");
//verify back link and click on it
backToPreviousPage("go back");
//verify title of index page again to make sure link is working
verifyTitle("Enter your name");
}
private void verifyTitle(String expectedTitle) {
//get the title of the page
String actualTitle = driver.getTitle();
// verify title
assertThat(actualTitle, equalTo(expectedTitle));
}
private void verifyHeaderMessage(String expectedHeaderMessage) {
// find header element
WebElement element = driver.findElement(By.tagName("h3"));
String actualHeaderMessage = element.getText();
// verify header text
assertThat(actualHeaderMessage, equalTo(expectedHeaderMessage));
}
private void enterUserName(String userName) {
// find the input text box
WebElement element = driver.findElement(By.name("userName"));
// set the user name in input text box
element.sendKeys(userName);
// submit form
element.submit();
}
private void backToPreviousPage(String expectedLinkText) {
// find the link by its id
WebElement element = driver.findElement(By.id("back"));
//get the actual link text
String actualLinkText = element.getText();
//verify link text with expected like text
assertThat(actualLinkText, equalTo(expectedLinkText));
// click the link
element.click();
}
}
Source: Test your web application’s UI with JUnit and Selenium
If you look closely at the comments in the above mentioned test class, you will be able to find how you can navigate to a page or how you can find an element to perform certain operations like get the text, set a value, trigger any event, etc.
UPDATE: Creating Executable JAR file.
Since you have your working JUnit test cases in place, you can use below snippet of main method and create an executable JAR file.
public static void main(String[] args) throws Exception {
JUnitCore.main("foo.bar.MyTestSuite");
}
Hope this makes for what you were looking for.
Shishir
Yes, you can. You just need to export as executable jar file.
If you want to make it fully independent, just include all lib and property files in a jar.
Here is the way in Eclipse: File/Export/Java/Runnable JAR file, after which select launch configuration and what else do you need to include in a jar.
By chance I have some code I wrote that already does this using maven which works well as an example. I uploaded it to github for you. See https://github.com/johndeverall/executablejarseleniumwebdriverdemo
If you run package.bat (in a windows environment) or follow the instructions in the README.md file, maven will build you an executable jar demonstrating selenium webdriver usage.
Read the pom.xml to discover how it works.
You will need to set up maven on your machine for this (if it is not setup already) but this is trivial and well worth doing in any case.
export it as jar file, Save it locally , Create a batch file and call the jar to execute your script.
Related
I am getting an error saying "The method window() is undefined for the type Object" and not sure why. This is what my code looks like:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Maximize2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.get("https://login.yahoo.com/");
driver.manage().window().maximize();
}
}
The snippet above works for me with Selenium 2.53.1, Firefox 51.0.1 and Fedora 25.
Try to update your Selenium and browser and run the test again.
Try to do the setup for Eclipse like this:
Download and unzip Selenium Client Driver for Java
http://seleniumhq.org/download/#client-drivers
Create a new project
Right click on project in Package Explorer
Click “Properties”, then “Java Build Path”
Click “Add External JARs” and select all jar files from “libs” folder and "selenium-java-$VERSION.jar"
Run the snippet again
You should also consider using Gradle for your dependency management. This tutorial and googling for "gradle selenium" should help: https://gradle.org/uncategorized/video-tutorial-test-automation-selenium-web-application/
I'm trying to follow along with the examples found on https://code.google.com/p/selenium/wiki/GettingStarted but I'm running into an issue with the package org.openqa.selenium.example being "incorrect". The rest of the code seems to be ok with the exception of the public class Example also having a red dot saying it needs to be declared, but I figured this is because the above package is having issues.
When I run the code, this is the out put:
Error: Could not find or load main class test.Test
/Users/me/Library/Caches/NetBeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 3 seconds)
I know there is a similar thread found here :Can't run Java example for Selenium / WebDriver, but with this being my first go at using both Java and Selenium, I'm still having a hard time trouble shooting this issue. In case you don't want to follow the link to the example, here is my code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.openqa.selenium.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class Example {
public static void main(String[] args) {
// Create a new instance of the html unit driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
WebDriver driver = new HtmlUnitDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("Cheese!");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
}
EDIT:
The package declaration is the package that your class Example is supposed to be in. It has to match the directory that your code is in, or else it won't compile.
Solution 1: Put your Example.java file should be in a directory like this:
[directory-to-your-project-root-or-source-folder]/org/openqa/selenium/example
Solution 2: Assuming your Example.java is already sitting directly in the root folder of your project, you can just remove the package declaration from the top of your Example.java file.
Solution 3: Declare your own package, like package com.jcmoney.example;, and then create a matching directory in your project com/jcmoney/example and put your Example.java file in it.
EDIT:
Based on the comments below and the screenshot added to the question:
See how it says "Source Packages", and below it "example" and then below it "Example.java"? Example.java is the file that your code is in. It is in the package "example".
So, quickest solution: Change your package declaration from "org.openqa.selenium.example" to just "example".
Your src package containing .java class is wrong. It should be org.openqa.selenium.example rather example. As the package declared inside class is not same as package declared outside. It threw a compile time error. Refactoring packaging to org.openqa.selenium.example outside in the src package or editing the org.openqa.selenium.example to example should fix the issue.
I started using selenide (selenium wrapper api) and must say its a great tool but my only issue is its lack of documentation or usage examples online yet.
Any idea how to run your application coded in selenide in google-Chrome. I am using eclipse as IDE. I have added an environment variable "browser" with value chrome in my run configuration but when I run it picks up firefox.
My stack is
JDBC
Java
Selenide
Try this
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
System.setProperty("selenide.browser", "Chrome");
open("http://google.com");
You can find some documentation here.
The below code will help you launch the Chrome Browser with Selenide, and not with the selenium. It means you don't have to issue a close or quit command at the end of the iteration.
import static com.codeborne.selenide.CollectionCondition.size;
import static com.codeborne.selenide.Condition.text;
import static com.codeborne.selenide.Selenide.*;
import org.junit.Rule;
import org.junit.Test;
import org.openqa.selenium.By;
import com.codeborne.selenide.junit.ScreenShooter;
public class SimpleDateFormatClass {
#Rule
public ScreenShooter takeScreenshotSelenide = ScreenShooter.failedTests().succeededTests();
#Test
public void checkGoogleSearchResultsReturnValidResultNumberAndText() {
System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver_2");
//Doesn't matter chrome or Chrome as this is case insensitive.
System.setProperty("selenide.browser", "Chrome");
open("http://google.com");
$(By.name("q")).setValue("Selenide").pressEnter();
// assure there are 10 results in the page
// static import shortcut, place the cursor on the method and press
// ctrl+shift+m/ cmd+shift+m
// $ -> driver.findElement, $$ -> driver.findElements
$$(".iris li.g").shouldHave(size(10));
$(".iris li.g").shouldHave(text("Selenide World!"));
}
}
This should help you even if you are running from the command prompt/ terminal, but if you want to exclusively pass on the Chrome from cmd you can use the "browser" parameter as below
-Dselenide.browser=chrome
You need to tell Selenide what browser to use. That can be done using Configuration properties:
import com.codeborne.selenide.Configuration;
public class Tests {
#Before
public void setBrowser() {
Configuration.browser = "chrome";
}
Remember: your webdriver should be placed on the standard path. For unix/linux it is: /usr/local/bin;
If your webdriver is located on a different path or renamed -- you need to set a system property with right path to the webdriver. For example:
Windows:
System.setProperty("webdriver.chrome.driver", "C:\\Program files\\chromedriver.exe");
Linux\Unix:
System.setProperty("webdriver.chrome.driver","/usr/share/chromedriver");
Make sure that your unix / linux chromedriver is executable. After this, you should have a fully working example (in my case, chromedriver is renamed and has version information):
import com.codeborne.selenide.*;
import org.openqa.selenium.*;
import org.junit.*;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.open;
import static com.codeborne.selenide.WebDriverRunner.getWebDriver;
public class TestClass {
#Before
public void setBrowser(){
Configuration.browser = "chrome";
Configuration.browserSize = "1920x1080";
Configuration.holdBrowserOpen = true;
System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver_2.33");
}
#Test
public void gotoGoogle(){
open("https://www.google.com");
WebElement searchBox = $(By.xpath("//input[#id='lst-ib']"));
$(searchBox).shouldBe(Condition.visible).setValue("How can I execute Selenide in Chrome using ChromeDriver").pressEnter();
WebElement firstResultLink = $(By.xpath("(//div[#class='rc']//a)[1]"));
$(firstResultLink).click();
System.out.println(getWebDriver().getCurrentUrl());
}
}
Another way is to use this command line switch with Maven:
mvn test -P chrome
It requires the Maven profiles in the pom.xml file such as are seen here:
https://github.com/selenide-examples/google
You can use System.setProperty("selenide.browser", "chrome"); for running in the chrome browser. If the same test you need to perform in safari just change the chrome to safari.
Eg:
System.setProperty("selenide.browser", "safari"); open("http://idemo.bspb.ru/");
I'm practicing building a test automation framework using Selenium Webdrive in Eclipse with Java, and as part of this I'm debugging through the code I have written so that I have a full understanding (I should note that when I run my tests outside of debug mode they work fine). The issue I have is that I keep encountering 'Source not found' errors in debug mode in respect of a whole load of stuff.
I've attached a screenshot below which shows my debug window in Eclipse, and shows an example of one of the errors.
So, the situation is that I have my TestRunner class from where I am running my tests (see code below)
package dataStructureModel;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestRunner {
public static void main(String[] args) {
FirefoxDriver driver = new FirefoxDriver();
List<iTest> tests = new ArrayList<iTest>();
// adding first test
tests.add((iTest) new DragDefaultTest001());
// adding second test
tests.add((iTest) new ColorCheckTest002());
BREAKPOINT HERE!
for(int i = 0; i < tests.size() ; i++)
{
iTest currentTest = tests.get(i);
currentTest.testSetup(driver);
boolean testResult = currentTest.runTest();
if(testResult)
{
System.out.println(currentTest.testName() + " test passed.");
}
else
{
System.out.println(currentTest.testName() + " test failed.");
}
currentTest.testCleanup();
}
}
}
I've set a breakpoint at the 'for' loop to iterate through my tests (I've not attached the code, given that as mentioned earlier, the tests do run). The Firefox browser loads up and I start stepping through and all looks good. Then I hit one of these 'Source not found' errors', of which there are many. I've attached a screenshot here, which gives an example....http://i.imgur.com/aDxCAX0.png
I know it asks to 'Edit Source Lookup Path', but I'm not sure what I should be referencing? As far as I'm aware I've attached all the selenium jar files, so I'm not sure where I'm going wrong.
This needs selenium-jar SOURCE files. In case you do no intend to see internals of Selenium Jars(which is a rare case), then just Step Over(F6) instead of Step Into(F5)
Hope this helps!
I am new to Eclipse and trying to run a simple selenium test.
However, I get the error message when I mouse over certain elements such as assertTrue with:
"void junit.framework.Assert.assterTrue(boolean condition)
Note: This element has no attached Javadoc and the Javadoc could not be found in the attached source."
I have added all the following referenced libraries (including the path details of their location on my PC):
selenium-java-2.0rc3.jar
selenium-java-2.0rc3-srs.jar
selenium-server-standalone-2.0rc3.jar
selenium-java-2.0b3.jar
selenium-java-2.0b3-srs.jar
Plus some junit files (4.7).
I have managed to fix similar problems with verifyText by opening the declaration and then trying to associate each selenium jar in turn until Eclipse recognises it. However, none of them seem to work with assertTrue. Does anyone have any idea which other Selenium downloads I should use if I need to do something else?
==================================================================================
Edit: I found the answer. I needed to link AssertTrue with one of the junit files instead!
==================================================================================
Paste of code below:
package com.eviltester.selenium2;
import com.thoughtworks.selenium.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.regex.Pattern;
public class MySecondSeleniumTest extends SeleneseTestCase {
#Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://www.google.co.uk/");
selenium.start();
}
#SuppressWarnings({ "deprecation", "deprecation" })
#Test
public void testSel1() throws Exception {
Selenium selenium2 = selenium;
selenium2.open("/search?source=ig&hl=en&rlz=&q=thetechnicalauthor+blog&aq=f&aqi=&aql=&oq=");
selenium2.click("link=The Technical Author: How to put keywords into your blog");
selenium2.waitForPageToLoad("30000");
*assertTrue*(selenium2.isElementPresent("//div[#class='mm']"));
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}
The error "This element has no attached Javadoc and the Javadoc could not be found in the attached source" indicates that the classpath for JDK is not set.
To find the exact path where java is installed give the below command:
which java
OUTPUT: /usr/bin/java Then set the path for JDK using the below commands:
export PATH=$PATH:/usr/bin/java
export JAVA_HOME=/usr/bin/java
To check whether the java path is set correctly give the below command:
java -version