我为Selenium自动化创建了一个Maven项目。能够通过“RunAs Configurations”从Eclipse执行测试,如下面的截图:
我能够毫无错误地执行mvn clean
和mvn package
。但是当我执行命令java -cp target\auto-0.0.1-SNAPSHOT.jar scripts.FirstMain
时,我收到如下错误:
D:\SeleniumProject>java -cp target\auto-0.0.1-SNAPSHOT.jar
scripts.FirstMain
Exception in thread "main" java.lang.NoClassDefFoundError: org/openqa/selenium/W
ebDriver
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.getMethod0(Unknown Source)
at java.lang.Class.getMethod(Unknown Source)
at sun.launcher.LauncherHelper.getMainMethod(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.openqa.selenium.WebDriver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
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)
... 6 more
D:\SeleniumProject>
的pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sample.test</groupId>
<artifactId>auto</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>autoTrial</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.53.1</version>
</dependency>
</dependencies>
</project>
我的代码是:
package scripts;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class FirstMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver wd = new FirefoxDriver();
wd.get("http://www.gmail.com");
wd.manage().window().maximize();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
wd.close();
wd.quit();
}
}
答案 0 :(得分:0)
您应该在类路径中添加您的lib目录。这样做:
java -cp "target\auto-0.0.1-SNAPSHOT.jar;target\lib\*" scripts.FirstMain
答案 1 :(得分:0)
异常是因为在运行时没有找到您的依赖项,一个解决方案是将该依赖项添加到您的类路径,或者您可以使用maven程序集插件将jar包装为所有依赖项。link here