我有一个方法,它使用HTTPClient生成一个我正在尝试模拟的RESTful get查询。下面是方法。
public static Properties getApplicationProperties(Long appId) {
GetMethod method = null;
Properties props = new Properties();
try {
String adminURL = System.getProperty(TrinityConstants.ADMIN_URL_KEY);
HttpClient client = new HttpClient();
method = new GetMethod(adminURL + "apps/" + appId);
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
LOGGER.warn("Method failed: " + method.getStatusLine());
return null;
}
byte[] responseBody = method.getResponseBody();
String result = new String(responseBody);
Gson gson = new Gson();
props = gson.fromJson(result, Properties.class);
}catch(Exception e){
LOGGER.warn("Failed to get application properties"
+ TrinityUtil.getStackTrace(e));
}finally{
if(null!=method){
method.releaseConnection();
}
}
return props;
}测试用例如下。我也不知道为什么!
@RunWith(PowerMockRunner.class)
@PrepareForTest( { GetMethod.class })
public class UtilTest {
@Test
public void testGetApplicationProperties() throws Exception{
GetMethod method = PowerMock.createMock(GetMethod.class);
org.powermock.api.easymock.PowerMock.expectNew(GetMethod.class, new Class[] {String.class}, "<The actual URL>").andThrow(new IOException("thrown from mock"));
PowerMock.replay(GetMethod.class);
Properties prop = Util.getApplicationProperties(2L);
PowerMock.verify(GetMethod.class);
}
}即使URL是相同的,我也会得到一个预期的失败异常,如下所示
java.lang.AssertionError:
Expectation failure on verify:
org.apache.commons.httpclient.constructors.GetMethod("<The actual URL>"): expected: 1, actual: 0
at org.powermock.api.easymock.internal.invocationcontrol.NewInvocationControlAssertionError.throwAssertionErrorForNewSubstitutionFailure(NewInvocationControlAssertionError.java:21)
at org.powermock.api.easymock.PowerMock.verifyClass(PowerMock.java:2279)
at org.powermock.api.easymock.PowerMock.verify(PowerMock.java:1646)
at 发布于 2015-05-12 00:06:00
我想你错过了重播模拟实例的机会。
PowerMock.replay(method,GetMethod.class);https://stackoverflow.com/questions/25025892
复制相似问题