2 qq 33777968 qq_33777968 于 2016.02.27 12:21 提问

PowerMockito来mock 构造函数的问题

public class HttpProtocolHandler {

private static HttpProtocolHandler httpProtocolHandler  = new HttpProtocolHandler();

public static HttpProtocolHandler getInstance() {
    return httpProtocolHandler;
}

   /**
 * 私有的构造方法
 */
private HttpProtocolHandler() {
    connectionManager= new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(200);
}

public TwoTuple<Integer,String> execute(HttpUriRequest request) throws Exception {

   //中间省略
    return new TwoTuple<Integer,String>(HttpStatus.SC_OK,null);
}
}

被测代码如上,测试代码如下,但是mock不生效。
我现在要mock HttpProtocolHandler.getInstance().execute(httpPost)的返回结果,测试代码哪里不对,新手求大神帮助解决,谢谢

@RunWith(PowerMockRunner.class)

@PrepareForTest(HttpProtocolHandler.class)
public class httpTest(){

@Test
public void test(){

    TwoTuple<Integer,String> rep = new TwoTuple<Integer, String>(1,"test1234567");

    HttpProtocolHandler mock = PowerMockito.spy(HttpProtocolHandler.getInstance());

    PowerMockito.whenNew(HttpProtocolHandler.class).withNoArguments().thenReturn(mock);
    PowerMockito.doReturn(rep).when(mock).execute((HttpUriRequest)Mockito.any());

    String url = "www";
    HttpPost httpPost = new HttpPost(url);
    TwoTuple<Integer,String> result11 = HttpProtocolHandler.getInstance().execute(httpPost);
    logger.info(result11.toString())
}

}

1个回答

devmiao
devmiao   Ds   Rxr 2016.02.28 07:00
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!