【发布时间】:2021-01-08 09:05:03
【问题描述】:
我在使用 Junit 5 进行 maven 测试时遇到了一个奇怪的问题。
我已经为每个方法创建了带有 junit 工具的测试套件,每个测试都是这样开始的。
private Class2Test createTestSubject() {
return new Class2Test();
}
public void test1() throws Exception {
Class2Test testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.getData();
//testing, assert
}
线
result = testSubject.getData();
返回 NullPointerException
当我通过 eclipse 执行相同的测试时,就可以了。定义了surefire插件
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.0</version>
</dependency>
</dependencies>
<configuration>
<systemPropertyVariables>
<entorno>${project.basedir}\resources\maqueta.properties</entorno>
<hibernate>${project.basedir}\resources\hibernate.cfg.xml</hibernate>
</systemPropertyVariables>
<parallel>classes</parallel>
<threadCount>10</threadCount>
</configuration>
</plugin>
我试图更改对象的声明以跟踪空指针,但它失败了。
Class2Test() 是默认构造函数,不需要参数或读取文件。
package test.com.my.myself;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import javax.annotation.Generated;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.tools.configuration.base.MethodRef;
import com.my.myself.Class2Test;
import com.google.gson.Gson;
import junitparams.JUnitParamsRunner;
@Generated(value = "org.junit-tools-1.1.0")
@RunWith(JUnitParamsRunner.class)
public class Tester1{
private Class2Test createTestSubject() {
return new Class2Test();
}
@DisplayName("TEST1")
@MethodRef(name = "test1", signature = "()QString;")
@Test
public void test1() throws Exception {
Class2Test testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.test1();
}
}
以及要测试的类
public class Class2Test{
private Connection conn = new Connector();
private static final Logger logger = Logger.getLogger(Class2Test.class);
public String test1() {
PrepareStatement pstm = conn.prepareStatement("select 1 from dual");
ResultSet rs = pstm.executeQuery();
...
return 1;
}
}
【问题讨论】:
-
createTestSubject 中有什么?让我猜猜——它会读取一些文件?
-
不读取文件,不配置参数,只创建一个dummy object来执行方法
-
你必须展示它,否则除了说testSubject为空之外没有人可以做任何事情。
-
Class2Test的构造函数是默认构造函数
-
从 surefire-plugin 配置中移除
junit-jupiter-engine依赖。您已将依赖项添加到 junit-jupiter 作为依赖项。同样如前所述,显示完整的测试,这意味着什么:I'd created the test suites with junit tools for each method...?测试套件通常是个坏主意...?
标签: java maven testing junit junit5