PowerMock期望失败

时间:2014-07-29 22:15:46

标签: java junit httpclient powermock getmethod

我有一个方法使用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 

0 个答案:

没有答案