2013-06-20 50 views
4

我的情況:PowerMock:嘲笑靜態方法,隻影響一個測試

我想添加一個新的測試。我需要嘲笑Service類的一個靜態方法X. 不幸的是,現有的測試正在以某種方式使用這種靜態方法。

當我使用PowerMock嘲笑X方法,然後其他測試失敗。 還有什麼我不應該接觸其他測試。

有沒有機會嘲笑一種測試的靜態方法? (使用PowerMock)。

在此先感謝。

+1

你能共享代碼? – DaveH

回答

1

當然,這是可能的!當你遇到問題的唯一時候是如果你想同時測試多個線程......我舉了一個如何在下面執行的例子。請享用。

import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.powermock.api.easymock.PowerMock; 
import org.powermock.core.classloader.annotations.PrepareForTest; 
import org.powermock.modules.junit4.PowerMockRunner; 

import static org.easymock.EasyMock.*; 

import static org.junit.Assert.*; 
@RunWith(PowerMockRunner.class) 
@PrepareForTest(IdGenerator.class) 
public class TestClass { 

    @Test 
    public void yourTest() 
    { 
     ServiceRegistrator serTestObj = new ServiceRegistrator(); 

     PowerMock.mockStatic(IdGenerator.class); 
     expect(IdGenerator.generateNewId()).andReturn(42L); 
     PowerMock.replay(IdGenerator.class); 
     long actualId = IdGenerator.generateNewId(); 

     PowerMock.verify(IdGenerator.class); 
     assertEquals(42L,actualId); 
    } 

    @Test 
    public void unaffectedTest() { 
     long actualId = IdGenerator.generateNewId(); 

     PowerMock.verify(IdGenerator.class); 
     assertEquals(3L,actualId); 
    } 
} 

的TestClass

public class IdGenerator { 
    public static long generateNewId() 
     { 
     return 3L; 
     } 
} 
0

解決您的問題的最簡單方法是創建新的測試課程並將測試放置在那裏。

您也可以在代碼中將隱藏在接口後面的常規類封裝起來,並將此接口存入您的測試中。

最後一件事,你可以嘗試使用是存根在@SetUp方法的靜態類的每個方法:

Mockito.when(StaticClass.method(PARAM))thenCallRealMethod();

和stub特定的方法在你的測試中使用: Mockito.when(Static.methodYouAreInterested(param))。thenReturn(value);