[英]How to mock a method to return something instead of throw exception (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();
}
}
是的,這是完全可能的。 您需要添加:
@PrepareForTest({OAuthUtil.class})
public class TestMine { //above this line
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.