Java 如何模拟一个方法来返回一些东西而不是抛出异常(PowerMock?)
我有一个方法,它执行一个测试,看看用户是否被授权,然后在其中包含一些我想要测试的其他逻辑,而不实际登录以授权我的用户 因此,我有一个static方法Java 如何模拟一个方法来返回一些东西而不是抛出异常(PowerMock?),java,junit,mocking,mockito,powermock,Java,Junit,Mocking,Mockito,Powermock,我有一个方法,它执行一个测试,看看用户是否被授权,然后在其中包含一些我想要测试的其他逻辑,而不实际登录以授权我的用户 因此,我有一个static方法OAuthUtil.retrieveAuthority(),它返回一个字符串,比如“domain” 我的构造函数类似于 public ImplService(){ String authority = OAuthUtil.retrieveAuthority(); //do something else } 我还有另外一个方法,就是我正
OAuthUtil.retrieveAuthority()
,它返回一个字符串,比如“domain”
我的构造函数类似于
public ImplService(){
String authority = OAuthUtil.retrieveAuthority();
//do something else
}
我还有另外一个方法,就是我正在尝试测试的方法,比如getList()
retrieveAuthority()
反过来,如果主题为null(它将始终为null),则可以抛出一个应用程序异常,但我想完全绕过它。因此,我希望我的mock返回一些东西(“域”),而不是抛出异常。可能吗
因此,我的测试现在是这样的,当遇到异常时,它会失败:
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