PowerMockito 和 Mockito 冲突

PowerMockito and Mockito conflict

我需要为遗留系统构建单元测试(使用 junit)。我需要测试的方法使用静态方法,我需要检查它是否被调用。所以,我需要使用 PowerMockito(对于 "regular" 模拟,我们使用 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>

我做错了什么?欢迎任何建议。

PowerMockito.doNothing().when(Application.class);

这是一个 stubbing 命令,但是 because you don't make a method call after the when(...), it's unfinished.

PowerMockito.doNothing().when(Application.class);
Application.someApplicationMethod();

您需要使用此语法,因为正常的 doVerb().when(foo) 语法会提供一个 实例 ,并且 Java 在尝试调用一个实例时经常发出警告基于实例而不是 class 名称的静态方法。

如果您想存根 Application 的所有方法,您可以将另一个参数传递给 mockStatic:

PowerMockito.mockStatic(Application.class, RETURNS_SMART_NULLS);