我需要为遗留系统构建单元测试(使用 junit)。我需要测试的方法使用静态方法,我需要检查它是否被调用。所以,我需要使用 PowerMockito(对于“常规”模拟,我们使用 mockito)。
但是,当我在测试中包含 PowerMockito 语句时,Mockito 失败并显示org.mockito.exceptions.misusing.UnfinishedStubbingException
. 如果我评论这些行PowerMockito.mockStatic(Application.class), PowerMockito.doNothing().when(Application.class) and PowerMockito.verifyStatic()
,UnfinishedStubbingException 不会发生,但是这样,我无法检查我的 IllegalArgumentException 是否发生。
被测方法如下所示:
public class ClientMB {
public void loadClient(Client client) {
try {
if (client == null) {
throw new IllegalArgumentException("Client is mandatory!");
}
setClient(clientService.findById(client.getId()));
} catch (Exception ex) {
Application.handleException(ex);
}
}
}
测试看起来像:
@PrepareForTest({ Application.class })
@RunWith(PowerMockRunner.class)
public class ClientMBTest {
@Test
public final void testLoadClient() {
ClientService mockedClientService = Mockito.mock(ClientService.class);
Mockito.when(mockedClientService.findById(42L)).thenReturn(new Client());
PowerMockito.mockStatic(Application.class);
PowerMockito.doNothing().when(Application.class);
ClientMB cmb = new ClientMB(mockedClientService);
mb.loadClient(null);
PowerMockito.verifyStatic();
}
}
我使用最新版本导入了 PowerMokito。
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
我做错了什么?欢迎任何建议。