When I am using the following Test method using JUnit 5 and JMockit, I am getting an error as:
JMockit didn't get initialized; please check the -javaagent JVM initialization parameter was used
These are my classes which I created and want to test:
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;
}
}
And this is my Test Implementation:
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());
}
}
Project Stack I have used:
- JDK 11.0.1
- Eclipse IDE 2020-03
- JUnit 5 (Added as library in Eclipse to project's classpath)
- JMockit 1.49 (Added as JAR)
Due to the above mentioned problem my test case is not passing. Any suggestions on how to resolve this issue? Or is there any other way to mock a static method?