Parvez Parvez - 6 months ago 29
Java Question

How to run a java program with selenium jar through command line

How to run a java program with selenium jar through command line...

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class HelloSelenium {

public static void main(String[] args)
{
WebDriver driver;

driver = new FirefoxDriver();
System.out.println("Hello");


}


}

I am getting following error on running it through CLI


java -cp ".;./jars/selenium-java-2.53.0.jar" HelloSelenium


Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/bas
e/Function
at HelloSelenium.main(HelloSelenium.java:11)
Caused by: java.lang.ClassNotFoundException: com.google.common.base.Function
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more

Answer

If you specify the classpath explicitly, the current directory is not included by default. So you should do

java -cp selenium-java-2.53.0.jar;. HelloSelenium

Note the extra ";.", e.g. adding . to classpath.

This will still be insufficient, however, as selenium itself has many other libraries as dependencies (included in the libs folder of your download). You will need to add those to your classpath as well.

Easiest to add them all with a wildcard for your simple example. So you should use:

java -cp selenium-java-2.53.0.jar;libs/*;. HelloSelenium

Note the "libs/*", which assumes you are in the root folder of your selenium download.

Comments