qq_33777968
qq_33777968
2016-02-27 04:21

PowerMockito来mock 构造函数的问题

  • java
  • mockito

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条回答

为你推荐

换一换