我正在尝试从命令行(Windows 10中的PowerShell)运行测试。 在问这个问题之前,我浏览了一些资料并阅读了很多主题,例如
但是当我尝试从PowerShell运行测试时,如JUnit Wiki
cd E:\Dev\AutoTest\Example
java -cp .;/libs/junit-4.12.jar;/libs/hamcrest-core-1.3.jar org.junit.runner.JUnitCore tests.Booking.BookingTests
我得到了输出
CommandNotFoundException
如果我通过旧命令行(cmd.exe
)运行相同的文件,
cd E:\Dev\AutoTest\Example
java -cp .;E:\Dev\AutoTest\Example\libs\junit-4.12.jar;E:\Dev\AutoTest\Example\libs\hamcrest-core-1.3.jar org.junit.runner.JUnitCore tests.Booking.BookingTests
我得到了输出
java.lang.IllegalArgumentException: Could not find class [tests.Booking.BookingTests] Caused by: java.lang.ClassNotFoundException: tests.Booking.BookingTests
在IDEA中,项目结构如下:
在硬盘上的结构如下:
•“ out”文件夹包含* .class文件
•“ src”文件夹包含* .java文件
问题:
如何使用我的结构从PowerShell中的命令行运行JUnit测试用例?
答案 0 :(得分:1)
在PowerShell中,分号是命令分隔符(允许您将两个语句放在一行上),因此您先运行java -cp .
(应输出命令帮助),然后运行/libs/junit-4.12.jar
(其中不被识别为命令)。 JUnit Wiki中的示例显然不是针对PowerShell的,而是针对CMD的,因为CMD使用与号(&
)来链接命令,因此该问题不会在那里发生。
此外,您将类路径中的路径设为绝对(/libs/junit-4.12.jar
),但是libs
目录位于项目文件夹中。这就是java
抱怨找不到类org.junit.runner.JUnitCore
的原因。从项目目录的根目录运行JUnit时,需要创建相对于该位置的路径。
并且由于您将代码编译到了其他文件夹(.\out\production\Afl_AutoTest
)中,因此也必须将该文件夹也添加到类路径中,否则JUnit将无法找到已编译的类(因为它们不在类路径)。
将类路径置于引号中,添加输出目录,并从库路径中删除前导斜杠,并且该命令应在CMD和PowerShell中均有效:
java -cp ".;out/production/Afl_AutoTest;libs/junit-4.12.jar;libs/hamcrest-core-1.3.jar" org.junit.runner.JUnitCore tests.Booking.BookingTests
更好的是,将所有参数定义为数组,然后splat将其定义:
$classpath = '.',
'out/production/Afl_AutoTest',
'libs/junit-4.12.jar',
'libs/hamcrest-core-1.3.jar'
$params = '-cp', ($classpath -join ';'),
'org.junit.runner.JUnitCore',
'tests.Booking.BookingTests'
java @params
尽管后者仅在PowerShell中起作用。
答案 1 :(得分:0)
最终命令必须包含所有“ libs”文件夹文件:
•java-client-4.1.2.jar
•junit-4.12.jar
•selenium-server-standalone-3.4.0.jar
•hamcrest-core-1.3.jar
java -cp ".;out/production/Afl_AutoTest;libs/java-client-4.1.2.jar;libs/junit-4.12.jar;libs/selenium-server-standalone-3.4.0.jar;libs/hamcrest-core-1.3.jar" org.junit.runner.JUnitCore tests.Booking.BookingTests
如果没有,输出将为
Exception in thread "main" java.lang.NoClassDefFoundError: org/openqa/selenium/Capabilities