2012-09-14 55 views
6
public class TestStatic { 
    public static int methodstatic(){ 
     return 3; 
    } 
} 


@Test 
@PrepareForTest({TestStatic.class}) 
public class TestStaticTest extends PowerMockTestCase { 

    public void testMethodstatic() throws Exception { 
     PowerMockito.mock(TestStatic.class); 
     Mockito.when(TestStatic.methodstatic()).thenReturn(5); 
     PowerMockito.verifyStatic(); 
     assertThat("dff",TestStatic.methodstatic()==5); 
    } 

    @ObjectFactory 
    public IObjectFactory getObjectFactory() { 
     return new org.powermock.modules.testng.PowerMockObjectFactory(); 
    } 
} 

例外:PowerMock靜態類不嘲笑

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'. 
For example: 
    when(mock.getArticles()).thenReturn(articles); 

Also, this error might show up because: 
1. you stub either of: final/private/equals()/hashCode() methods. 
Those methods *cannot* be stubbed/verified. 
2. inside when() you don't call method on mock but on some other object. 

我的IntelliJ通過運行它,舊的代碼有很多的方法...

有人有想法和我去通過官方tuto,無意讓這個簡單的測試工作

回答

0

看一看這個答案:Mocking Logger and LoggerFactory with PowerMock and Mockito

如果要存根靜態調用但不應使用Mockito.whenPowerMockito.when

靜態是一種可測試性的噩夢,您儘可能避免這種情況,並且爲了不再使用靜態或不必使用PowerMock技巧來測試您的生產代碼而重新設計您的設計。

希望有所幫助。

乾杯, 布萊斯

+0

謝謝,是啊,你不選擇遺留代碼:),但你可以重構......虐待靜態模擬和應用可嘲弄的模式。 – Sam

+0

同意的遺留代碼是一個痛苦,PowerMock確實在這些情況下是強大的:) – Brice

+1

這只是不正確的:「如果你想存根靜態調用,你也不應該使用'Mockito.when'」。 PowerMockito使用頁面在其示例代碼中使用'Mockito.when'。 – ach

3

我看了看我的遺留代碼的測試,我可以看到的是,你叫PowerMockito.mock(TestStatic.class),而不是PowerMockito.mockStatic(TestStatic.class)。如果您使用PowerMockito.when(...)Mockito.when(...),則無關緊要,因爲第一個人只是委託給第二個人。

還有一點評論:我知道也許你必須測試一個遺留代碼。也許你可以用JUnit4風格做到這一點,而不是產生遺留測試? Brice提到的例子是一個很好的例子。

5

我發現在我的情況下,這種問題的解決方法,希望與大家分享:

如果我打電話給在測試類的嘲笑方法:

@RunWith(PowerMockRunner.class) 
@PrepareForTest(Calendar.class) 
public class TestClass { 
    @Test 
    public void testGetDefaultDeploymentTime() 
    PowerMockito.mockStatic(Calendar.class); 
    Calendar calendar = new GregorianCalendar(); 
    calendar.set(Calendar.HOUR_OF_DAY, 8); 
    calendar.set(Calendar.MINUTE, 0); 
    when(Calendar.getInstance()).thenReturn(calendar); 
    Calendar.getInstance(); 
    } 
} 

它的工作就好了。但是當我重新編譯測試時,它在另一個類中調用了Calendar.getInstance(),它使用了真正的Calendar方法。

@Test 
public void testGetDefaultDeploymentTime() throws Exception { 
    mockUserBehaviour(); 
    new AnotherClass().anotherClassMethodCall(); // Calendar.getInstance is called here 
} 

所以,作爲一個解決方案,我加入AnotherClass.class到@PrepareForTest和現在的工作。

@PrepareForTest({Calendar.class, AnotherClass.class}) 

看來PowerMock需要知道在哪裏調用靜態方法。

+0

雖然這看起來不像是一個靜態方法調用,但您只需調用對象上的方法即可! –