问题描述
- 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()) }
}
解决方案
http://blog.csdn.net/knighttools/article/details/44630975
时间: 2024-11-02 16:16:05