我有Spring Controller,其中一个接口是自动接线的,如以下课程所示。
@Controller
public class EmployeeController
{
@Autowired
private EmployeeManager employeeManager;
public int saveEmployee(Employee employee) {
int empId = employeeManager.saveEmployee(employee);
return empId;
}
}
现在,我创建了一个Junit测试类,如下所示。
public class EmployeeControllerTest {
private EmployeeController employeeController ;
private EmployeeManager employeeManager ;
@Before
public void setUp() throws Exception {
employeeController = PowerMockito.spy(new EmployeeController());
employeeManager = PowerMockito.mock(EmployeeManager.class);
}
@Test
public void shouldGetCountOfEmployees()
{
Employee emp = new Employee("Peter");
int empId = employeeController.saveEmployee(emp);
Assert.assertEquals(1, empId);
}
现在,在执行测试类之后,我在控制器的
int empId = employeeManager.saveEmployee(employee);
方法内的行saveEmployee
处获取了nullPointerException。我也尝试了@Mock注释,@ Spy注释,但无法执行测试用例。
因此,在使用PowerMockito执行测试用例时,请帮助在控制器中注入
employeeManager
实例。谢谢
最佳答案
您必须使用Whitebox.setInternalState将模拟注入到EmployeeController中。
范例:
Whitebox.setInternalState(EmployeeController, "employeeManager", employeeManager) ;