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:
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?
I had the same error while trying to use JMockit 1.49. I also came across this link and made sure that my JMockit jar comes before the JUnit jar in the classpath. However, this did not work in my case.
As already suggested, the error message gives you the solution:
check the -javaagent JVM initialization parameter
In eclipse, go to the run configurations (Run > Run Configurations). Then select the one you are using to run the JUnit tests. Under the tab "Arguments" you have to add the following line:
-javaagent:path-to-your-jmockit-jar/jmockit-1.49.jar
Then you should be fine!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With