2015-08-14 163 views
0

我需要爲遺留系統構建單元測試(使用junit)。我需要測試的方法使用靜態方法,我需要檢查它是否被調用。所以,我需要使用PowerMockito(對於「常規」嘲笑,我們使用mockito)。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> 

我在做什麼錯了?任何建議是受歡迎的。

回答

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);