Selenium Webdriver Example issue - java

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.

Related

Making executable file in Selenium WebDriver with Java

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.

java - duplicate class

Confused as to why I get duplicate class error for the following code?
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package database_console;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* #author davidsonr
*/
public class DBConnect {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
Netbeans highlights DBConnect as red with duplicate class error.
This is a known issue with netbeans BUG 226360
it might help to clear Netbeans cache:
Go to Help -> About and you will see
Cache directory: Path\to\Directory
Close NetBeans, go to specified directory and delete everything.
This can also happen if the package name does not match the folder name, or if the package name is omitted. Check the package statement in your source.
this might be due to 2 classes with the same name in the same package
This also happens if your referencing the erroring class in a separate file in the same package, with the erroring class with an unmatching package path to the file where you are referencing erroring class.
For example
file 1
some.incorrect.path.package
class_that_is_erroring{
}
file 2
some.correct.path.package
class new_class{
class_that_is_erroring myclass = null;
}
The package paths in both files must match each other and match the file system directory.
If the file name doesn't match the class name, NetBeans 8.0.1 will report this as a duplicate class.
A new answer... In this case, the duplicate class error was confusing. So was part of the next error, but it also pointed to the real problem and the fix.
From my log file:
Error 1: a\g\GoodClass error:duplicate class: a.g.GoodClass //Not the problem
Error 2: a\b\BadClass error: cannot access GoodClass //The problem
bad source file: a\g\GoodClass //No, it's fine
file does not contain class x.y.GoodClass //How to fix it
Please remove or make sure it appears in the correct subdirectory of the sourcepath.
Java reports the first line of Error 2 because BadClass is using a wildcarded import, either import x.*; or import x.y.*;. The java compiler found x.y.GoodClass first, so couldn't determine which you really wanted: a.g.GoodClass or x.y.GoodClass.
THE FIX: remove the wildcarded import and add the specific imports you need from library x.y.

package org.apache.commons.lang does not exist [Netbeans]

Am new to programming with basic knowledge and I've taken a liken to Java.
I wanted to write a code that calculates a number to the nth power without using loops. I've been trying to use the repeat method from "commons lang" which i came to know about, about 4 days ago. I Found a lot of info in this site and others that helped me in understanding how to use this packed.
So far I downloaded commons-lang3-3.1 then kept the folder in the same folder as my project and added the jar file to my project's library by:-
right clicking on libraries
1 then Add JAR/Folder
2 then i opened the commons-lang3-3.1 folder
3 and selected "commons-lang3-3.1.jar" from a number of 4 selections:
commons-lang3-3.1.jar
commons-lang3-3.1-javadoc.jar
commons-lang3-3.1-sources.jar
commons-lang3-3.1-tests.jar
here is a code that am using to test that i got from one of the the other questions:-
0. package refreshingmemory;
1. import org.apache.commons.lang.StringUtils;
2. public class RefreshingMemory {
3.
4. public static void main(String[] args) {
5. String str = "abc";
6. String repeated = StringUtils.repeat(str, 3);
7. repeated.equals("abcabcabc");
8.
9. }
10. }
line 1 says package org.apache.commons.lang does not exist.
line 7 says Should check the method return value
and if i remove line 1 i get a cannot find symbol at line 6
How do I get a successfully import ?
Screenshot of Netbeans:
http://commons.apache.org/proper/commons-lang/ states the following:
Note that Lang 3.0 (and subsequent versions) use a different package (org.apache.commons.lang3) than the previous versions (org.apache.commons.lang), allowing it to be used at the same time as an earlier version.
So change the package accordingly, or heed Richard Tingle's advice and left click the error+light bulb icon in the gutter (were line numbers are shown) and choose "Add import for...".
import org.apache.commons.lang3.StringUtils;

can I load user packages into eclipse to run at start up and how?

I am new to java and to the eclipse IDE.
I am running Eclipse
Eclipse SDK
Version: 3.7.1
Build id: M20110909-1335
On a windows Vista machine.
I am trying to learn from the book Thinking in Java vol4.
The author uses his own packages to reduce typing. However the author did not use Eclipse and this is where the problem commes in..
This is an example of the code in the book.
import java.util.*;
import static net.mindview.util.print.*;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("hello world");
print("this does not work");
}
this is the contents of print.Java
//: net/mindview/util/Print.java
// Print methods that can be used without
// qualifiers, using Java SE5 static imports:
package net.mindview.util;
import java.io.*;
public class Print {
// Print with a newline:
public static void print(Object obj) {
System.out.println(obj);
}
// Print a newline by itself:
public static void print() {
System.out.println();
}
// Print with no line break:
public static void printnb(Object obj) {
System.out.print(obj);
}
// The new Java SE5 printf() (from C):
public static PrintStream
printf(String format, Object... args) {
return System.out.printf(format, args);
}
} ///:~
The error I get the most is in the statement.
Import static net.mindview.util.print.*;
On this staement the Eclipse IDE says it cannot resolve net
also on the
print("this does not work");
The Eclipse IDE says that the class print() does not exist for the class HelloWorld.
I have been trying to get these to work, but with only limited success, The autor uses another 32 of these packages through the rest of the book.
I have tried to add the directory to the classpath, but that seems to only work if you are using the JDK compiler. I have tried to add them as libraries and i have tried importing them into a package in a source file in the project. I have tried a few other things but cant remember them all now.
I have been able to make one of the files work, the print.java file I gave the listing for in this message. I did that by creating a new source folder then making a new package in that foldeer then importing the print.java file into the package.
But the next time I try the same thing it does not work for me.
What I need is a way to have eclipse load all these .java files at start up so when I need them for the exercises in the book they will be there and work for me, or just an easy way to make them work everytime.
I know I am not the only one that has had this problem I have seen other questions about it on google searches and they were also asking about the Thinking In Java book.
I have searched this site and others and am just not having any luck.
Any help with this or sugestions are welcome and very appreciated.
thank you
Ok I have tried to get this working as you said, I have started a new project and I removed the static from the import statement, I then created a new source folder, then I created a new package in the source folder. Then I imported the file system and selected the the net.mindview.util folder.
Now the immport statement no longer gives me an error. But the the print statement does, the only way to make the print statement work is to use its fully qualified name. Here is the code.
import net.mindview.util.*;
public class Hello2 {
public static void main(String[] args) {
Hello2 test = new Hello2();
System.out.println();
print("this dooes not work");
net.mindview.util.Print.print("this stinks");
}
}
The Error on the print statement is:
The method print(String) is undefined for the type Hello2
and if I try to run it the error I get is:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method print(String) is undefined for the type Hello2
at Hello2.main(Hello2.java:6)
The Statement::::: net.mindview.util.Print.print("this stinks") is the fully qualified print statement and it does not throw an error but it does totally defeat the purpose of the print.java file..
If you have any questions please ask Ill get back to you as soon as I can.
I've had similar issues. I solved it by following the steps below:
Click File->New->Java Project. Fill in UtilBuild for the ProjectName. Chose the option "Use project folder as root and click 'Finish'.
Right-click on UtilBuild in the PackageExplorer window and click New->package. For the Package Name, fill in net.mindview.util
Navigate within the unzipped Thinking In Java (TIJ) folder to TIJ->net\mindview\util. Here you will find all the source code (.java) files for util.
Select all the files in the net\mindview\util folder and drag them to the net.mindview.util package under UtilBuild in Eclipse. Chose the 'Copy Files' option and hit 'OK'.
You will probably already have the 'Build Automatically' option checked. If not, go to Project and click 'Build Automatically'. This will create the .class files from the .java source files.
In Eclipse, right-click on the project you were working on (the one where you couldn't get that blasted print() method to work!) Click Properties and Java Build Path->Libraries. Click 'Add Class Folder...' check the box for UtilBuild (the default location for the .class files).
I think the confusion here arises due to CLASSPATH. If you use Eclipse to build and run your code then Eclipse manages your CLASSPATH. (You don't have to manually edit CLASSPATH in the 'Environment Variables' part of your computer properties, and doing so changes nothing as far as Eclipse Build and Run are concerned.)
In order to call code that exists outside your current project (I will name this 'outside code' for convenience) you need to satisfy three things:
A. You need to have the .class files for that code (as .class files or inside a JAR)
B. You need to indicate in your source code where to look for the 'outside code'
C. You need to indicate where to start looking for the 'outside code'
In order to satisfy these requirements, in this example we:
A. Build the project UtilBuild which creates the .class files we need.
B. Add the statement import static net.mindview.util.Print.*; in our code
C. Add the Class Folder library in Eclipse (Java Build Path->Libraries).
You can investigate the effect of Step C by examining the .classpath file that lives directly in your project folder. If you open it in notepad you will see a line similar to the following:
<classpathentry kind="lib" path="/UtilBuild>
You should combine this with your import statement to understand where the compiler will look for the .class file. Combining path="/UtilBuild" and import static net.mindview.util.Print.*; tells us that the compiler will look for the class file in:
UtilBuild/net/mindview/util
and that it will take every class that we built from the Print.java file (Print.*).
NOTE:
There is no problem with the keyword static in the statement
import static net.mindview.util.Print.*;
static here just means that you don't have to give specify the class name from Print.java, just the methods that you want to call. If we omit the keyword static from the import statement, then we would need to qualify that print() method with the class it belongs to:
import net.mindview.util.Print.*;
//...
Print.print("Hello");
which is slightly more verbose than what is achieved with the static import.
OPINION:
I think most people new to Java will use Eclipse at least initially. The Thinking in Java book seems to assume you will do things via command line (hence it's guidance to edit environment variables in order to update CLASSPATH). This combined with using the util folder code from very early in the book I think is a source of confusion to new learners of the language. I would love to see all the source code organised into an Eclipse project and available for download. Short of that, it would be a nice touch to include the .class files in just the 'net/mindview/util' folder so that things would be a little easier.
U should import package static net.mindview.util not static net.mindview.util.Print
and you should extend the class Print to use its method.......
You should remove the static keyword from your import decleration, this: import static net.mindview.util.print.*; becomes this: import net.mindview.util.print.*;
If that also does not work, I am assuming you did the following:
Create your own project;
Start copying code directly from the book.
The problem seems to be that this: package net.mindview.util; must match your folder structure in your src folder. So, if your src folder you create a new package and name it net.mindview.util and in it you place your Print class, you should be able to get it working.
For future reference, you should always make sure that your package decleration, which is at the top of your Java class, matches the package in which it resides.
EDIT:
I have seen your edit, and the problem seems to have a simple solution. You declare a static method named print(). In java, static methods are accessed through the use of ClassName.methodName(). This: print("this dooes not work"); will not work because you do not have a method named print which takes a string argument in your Hello2 class. In java, when you write something of the sort methodName(arg1...), the JVM will look for methods with that signature (method name + parameters) in the class in which you are making the call and any other classes that your calling class might extend.
However, as you correctly noted, this will work net.mindview.util.Print.print("this stinks");. This is because you are accessing the static method in the proper way, meaning ClassName.methodName();.
So in short, to solve your problem, you need to either:
Create a method named print which takes a string argument in your Hello2 class;
Call your print method like so: Print.print("this stinks");
Either of these two solutions should work for you.
In my case I've dowloaded and decompressed the file TIJ4Example-master.zip. in eclipse workspace folder. The three packages : net.mindview.atunit, net.mindview.simple and net.mindview.util are in this point of the project :
and java programs runs with no problems (on the right an example of /TIJ4Example/src/exercises/E07_CoinFlipping.java)

Eclipse / Selenium unable to locate correct library for verifyText, isElementPresent etc

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

Categories