首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PowerMock期望失败

PowerMock期望失败
EN

Stack Overflow用户
提问于 2014-07-30 06:15:46
回答 1查看 908关注 0票数 0

我有一个方法,它使用HTTPClient生成一个我正在尝试模拟的RESTful get查询。下面是方法。

代码语言:javascript
复制
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;
    }

测试用例如下。我也不知道为什么!

代码语言:javascript
复制
@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是相同的,我也会得到一个预期的失败异常,如下所示

代码语言:javascript
复制
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 
EN

回答 1

Stack Overflow用户

发布于 2015-05-12 00:06:00

我想你错过了重播模拟实例的机会。

代码语言:javascript
复制
PowerMock.replay(method,GetMethod.class);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25025892

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档