PowerMockito和Mockito发生冲突

时间:2015-08-14 14:58:58

标签: junit mockito powermockito

我需要为遗留系统构建单元测试(使用junit)。我需要测试的方法,使用静态方法,我需要检查它是否被调用。因此,我需要使用PowerMockito(对于"常规"模拟,我们使用mockito)。

但是,当我在测试中包含PowerMockito语句时,Mockito失败了org.mockito.exceptions.misusing.UnfinishedStubbingException。如果我对行PowerMockito.mockStatic(Application.class), PowerMockito.doNothing().when(Application.class) and PowerMockito.verifyStatic()进行注释,则不会发生UnfinishedStubbingExceptiondoes,但是这样,我无法检查是否发生了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>

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

1 个答案:

答案 0 :(得分:2)

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

这是存根命令,但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在尝试基于实例而不是基于实例调用静态方法时经常发出警告班级名称。

如果要存储所有应用程序的方法,可以通过将另一个参数传递到mockStatic来实现:

PowerMockito.mockStatic(Application.class, RETURNS_SMART_NULLS);