如何将方法模拟为 return 而不是抛出异常(PowerMock?)
How to mock a method to return something instead of throw exception (PowerMock?)
我有一个方法可以执行测试以查看用户是否已获得授权,然后在其中包含一些我想测试的其他逻辑,而无需实际登录以授权我的用户。
所以,我有这个 static 方法 OAuthUtil.retrieveAuthority()
其中 return 是一个字符串,比方说 "domain".
我的构造函数类似于
public ImplService(){
String authority = OAuthUtil.retrieveAuthority();
//do something else
}
我还有另一种方法,这是我实际尝试测试的方法,比如 getList()
。
如果 Subject 为 null,retrieveAuthority()
又会抛出 WebApplicationException,它永远是 null,但我想完全绕过它。所以,我希望我的模拟 return 某些东西 ("domain") 而不是抛出异常。这可能吗?
所以,我现在的测试是这样的,遇到异常就失败了:
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
我有一个方法可以执行测试以查看用户是否已获得授权,然后在其中包含一些我想测试的其他逻辑,而无需实际登录以授权我的用户。
所以,我有这个 static 方法 OAuthUtil.retrieveAuthority()
其中 return 是一个字符串,比方说 "domain".
我的构造函数类似于
public ImplService(){
String authority = OAuthUtil.retrieveAuthority();
//do something else
}
我还有另一种方法,这是我实际尝试测试的方法,比如 getList()
。
retrieveAuthority()
又会抛出 WebApplicationException,它永远是 null,但我想完全绕过它。所以,我希望我的模拟 return 某些东西 ("domain") 而不是抛出异常。这可能吗?
所以,我现在的测试是这样的,遇到异常就失败了:
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