当我使用 JUnit 5 和 JMockit 使用以下测试方法时,出现错误:
JMockit 没有初始化;请检查是否使用了-javaagent JVM初始化参数
这些是我创建并想要测试的课程:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Employee
{
private Integer empId;
private String empName;
public Employee(Integer empId,String empName)
{
this.empId = empId;
this.empName = empName;
}
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
}
class EmployeeDAO
{
private static List<Employee> employeeList = new ArrayList<Employee>();
static
{
Employee e1 = new Employee(1001, "John");
Employee e2 = new Employee(1002, "Jack");
Collections.addAll(employeeList, e1,e2);
}
public static List<Employee> getEmployeeList() {
return employeeList;
}
public static void setEmployeeList(List<Employee> employeeList) {
EmployeeDAO.employeeList = employeeList;
}
}
class EmployeeService
{
public List<Employee> getEmployees()
{
List<Employee> empListFromDao = new ArrayList<Employee>();
try
{
empListFromDao = EmployeeDAO.getEmployeeList();
}
catch(Exception e)
{
throw e;
}
return empListFromDao;
}
}
这是我的测试实现:
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import mockit.Mock;
import mockit.MockUp;
import mockit.integration.junit5.JMockitExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ExtendWith(JMockitExtension.class)
public class EmployeeTest
{
@Test
public void testMethodForStaticMock$FromService()
{
new MockUp<EmployeeDAO>()
{
@Mock
public List<Employee> getEmployeeList()
{
return new ArrayList<Employee>();
}
};
EmployeeService service = new EmployeeService();
assertEquals(0,service.getEmployees().size());
}
}
我使用过的项目堆栈:
由于上述问题,我的测试用例没有通过。 关于如何解决这个问题有什么建议吗?或者还有其他方法来模拟静态方法吗?
我在尝试使用 JMockit 1.49 时遇到了同样的错误。我还遇到了 this 链接,并确保我的 JMockit jar 位于类路径中的 JUnit jar 之前。然而,这对我来说不起作用。
正如已经建议的,错误消息为您提供了解决方案:
检查-javaagent JVM初始化参数
在 Eclipse 中,转到运行配置(运行 > 运行配置)。然后选择您用于运行 JUnit 测试的测试。在“参数”选项卡下,您必须添加以下行:
-javaagent:path-to-your-jmockit-jar/jmockit-1.49.jar
那你应该没问题!
将以下内容添加到 pom.xml
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<argLine>-javaagent:${settings.localRepository}/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar</argLine>
</configuration>
</plugin>
将以下内容添加到您的 gradle 文件中,这是链接 https://jmockit.github.io/tutorial/Introduction.html#runningTests
test {
jvmArgs "-javaagent:${classpath.find { it.name.contains("jmockit") }.absolutePath}"
}