我正在尝试在测试类中运行单个测试,但该类中的所有测试都会运行。
我是这样运行的
mvn clean test -Dtest=TestClass#testMethod
我已经尝试过
mvn clean test -Dtest="TestClass#testMethod"
和
mvn clean test "-Dtest=TestClass#testMethod"
但似乎没有任何效果。TestClass 中的所有测试都运行...
我在这里想念什么?
测试路径:/development/src/test/java/com/company/project/TestClass.java
测试类.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestClass {
@Test
public void testMethod1() throws Exception {
System.out.println("running1");
}
@Test
public void testMethod2() throws Exception {
System.out.println("running2");
}
}
来自的输出 mvn -Dtest=TestClass#testMethod1 clean test
[INFO]
[INFO] --- maven-surefire-plugin:2.19.1:test (default-test) @ lazarus ---
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running TestClass
SLF4J: Class path contains multiple SLF4J bindings.
..
running1
running2
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.536 sec - in TestClass
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 50.452 s
[INFO] Finished at: 2017-03-01T13:42:51-05:00
[INFO] Final Memory: 41M/1781M
[INFO] ------------------------------------------------------------------------
编辑 2:电源模拟依赖导致问题?
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-mockito-release-full</artifactId>
<version>1.6.4</version>
<classifier>full</classifier>
<scope>test</scope>
</dependency>
这是一个棘手的错误。的powermock-mockito-release-full
依赖带来在classpath TestNG的,和你想运行使用JUnit测试,因为测试方法是使用JUnit注解org.junit.Test
注释。这就是故障的原因。
当您没有指定使用哪个提供程序来运行测试时,Surefire 插件会尝试聪明地为您检测它。目的是如果您依赖于TestNG,它将自动选择其TestNG提供程序来运行您的测试。相反,如果您依赖 JUnit,它将使用其 JUnit 提供程序。这甚至取决于 TestNG 或 JUnit 的版本。这对于简化配置非常有用,但是当两者都在类路径上时......未指定会发生什么。事实证明,Surefire 2.19.1 将首先选择 TestNG(参见自动检测提供者的源代码,并且TestNG 在知名提供者列表中的任何 JUnit 特定提供者之前指定)。您可以检查是否是在调试模式下查看日志的情况(使用-X
);开始测试时,你会看到
Running com.company.project.TestClass
Configuring TestNG with: TestNG60Configurator
证明正在使用TestNG提供程序。
这里会有几个解决方案。首先,在测试类路径上同时使用 TestNG 和 JUnit 可能不是您想要的,除非您明确希望在测试中使用这两个框架。因此,最简单的解决方案是将 TestNG 完全排除为 的传递依赖项powermock-mockito-release-full
,这样它就不会出现在测试类路径中,并且确实添加
<exclusions>
<exclusion>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
</exclusion>
</exclusions>
解决了这个问题,并且只有 1 个测试在正确的-Dtest=TestClass#testMethod1
调用下运行。
也许更好的第二个解决方案是消除对它的依赖,powermock-mockito-release-full
它会在测试类路径上带来许多您很可能不想要的其他东西。值得注意的是,它甚至带来了源 JAR!如果您只依赖powermock-module-junit4
,则问题也已解决,而不会弄乱您的类路径。您可以自己添加对 Mockito 或其他您需要的特定组件的依赖。
第三种解决方案是强制使用 JUnit 47 提供程序。这将确保测试使用 JUnit 而不是 TestNG 运行,即使两者都在测试类路径中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句