我有一个方法,可以执行测试以查看用户是否获得授权,然后在其中包含一些我想要测试的其他逻辑,而无需实际登录来授权我的用户。
所以,我有这个静态方法OAuthUtil.retrieveAuthority()
,它返回一个字符串,比方说“domain”。
我的构造函数类似于
public ImplService(){
String authority = OAuthUtil.retrieveAuthority();
//do something else
}
我还有另一种方法,这是我实际上正在尝试测试的方法,例如 getList()
。
retrieveAuthority()
反过来会抛出 WebApplicationException,它永远都是空,但我想完全绕过这个。所以,我希望我的模拟返回一些东西(“域”)而不是抛出异常。这可能吗?
所以,我现在的测试是这样的,当遇到异常时它会失败:
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
关于java - 如何模拟方法以返回某些内容而不是抛出异常(PowerMock?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36634993/