2016-04-14 48 views
1

我有一個方法,執行一個測試,看看用戶是否被授權,然後有一些其他的邏輯,我想測試,而沒有實際登錄授權我的用戶。如何嘲笑方法返回的東西,而不是拋出異常(PowerMock?)

所以,我有這個靜態方法OAuthUtil.retrieveAuthority()它返回一個字符串,讓我們說「域」。

我的構造是一樣的東西

public ImplService(){ 
    String authority = OAuthUtil.retrieveAuthority(); 
    //do something else 
} 

我有另一種方法,是一個我其實是想測試一下,說getList()

retrieveAuthority()反過來可以拋出aWebApplicationException如果主體爲空,它將永遠是,但我想完全繞過這一點。所以,我希望我的模擬返回一些東西(「域」),而不是拋出異常。那可能嗎?

所以,我的測試是這樣的,現在,它失敗在遇到異常時:

import org.junit.Before; 
import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.powermock.api.mockito.PowerMockito; 
import org.powermock.modules.junit4.PowerMockRunner; 

@RunWith(PowerMockRunner.class) 
public class TestMine { 
    public ImplService impl; 

    @Before 
    public void setUp() { 
     PowerMockito.mockStatic(OAuthUtil.class); 
     PowerMockito.when(OAuthUtil.retrieveAuthority()).thenReturn("domain"); 
     ImplService impl = new ImplService(); 
    } 

    @Test 
    public void getListTest() throws NotFoundException { 
     Response response = impl.getList(); 
    } 
} 

回答

2

是的,它是完全可能的。您需要添加:

@PrepareForTest({OAuthUtil.class}) 
public class TestMine { //above this line 
相關問題