如何使用 Mockito 模拟 class 级别的方法声明

How to mock class level method declaration using Mockito

我有一个测试 class 如下所示,我试图通过它来复制我当前的问题。

public class EmployeeResource{
public EmployeeAPI restApi = (EmployeeAPI) EmpRegistrar.getInterface(EmployeeAPI.class); // getInterface is a static method.

public Employee addEmployee( Employee emp){
if(Objects.isNull(emp)) {
restApi.notifyAudit(); // suppose this is some existing legacy code which we don't want to run while running junit.
throw new APIException(CLIENT_ERROR_BAD_REQUEST, “Incorrect Post Request”);
}
// Implementation
}

现在我有了 Junit class。

@RunWith(PowerMockRunner.class)
@PrepareForTest({ EmpRegistrar.class })
public class EmployeeResourceTest {

@Before
public void setup() throws Exception {
PowerMockito.mockStatic(EmpRegistrar.class);
EmployeeAPI restApi= Mockito.mock(EmployeeAPI.class);
PowerMockito.when(EmpRegistrar.getInterface(EmployeeAPI.class)).thenReturn(restApi);
PowerMockito.doNothing().when(restApi).notifyAudit();
}

@Test
public void testAddEmployee_Invalid() throws Exception {
EmployeeResource employeeResource = new EmployeeResource();
 try {
employeeResource.addEmployee(null);
}
catch (Exception e) {
assertTrue(e instanceof APIException);
assertEquals("Incorrect Post Request", e.getMessage());
}
}
}

所以当我 运行 上述 junit 时,我没有得到 restApi 对象的模拟实例并将其作为 null 获取,这在下面的行中给出了 NullPointerException

restApi. notifyAudit(); // when it runs through junit.

只是为了验证,当我在 addEmployee 方法本身中添加行 restApi = (EmployeeAPI) EmpRegistrar.getInterface(EmployeeAPI.class); 时,我得到了模拟实例并且测试用例通过了。

所以只想和你们所有人核实一下,因为 restApi 的对象实例是在 class 级别获得的,所以我无法通过 mockito 获取它的模拟实例,因为mockito 的范围适用于该方法 itself.Or 有什么方法可以实现相同的目的。

这是一个现有的旧代码,我正在为我的项目编写 junit。我试图通过上面的示例测试复制相同的内容 code.So 如果我在任何地方不清楚,请告诉我。

谢谢 -山姆

使用 powermock:

EmployeeResource employeeResource = new EmployeeResource();
Whitebox.setInternalState(employeeResource, restApi);

如果你有依赖关系spring-test

EmployeeResource employeeResource = new EmployeeResource();
ReflectionTestUtils.setField(employeeResource, "restApi", restApi);

我试图重现这个问题,但我做不到。您使用的 Mock/PowerMock 是什么版本?