如何使用Mockito模拟构造函数

时间:2016-07-25 13:17:40

标签: spring unit-testing mockito powermock powermockito

我有一个这样的课程:

public class A {

public Integer callMethod(){
  return someMethod();
}


private Integer someMethod(){
  //Some Code
  HttpPost httpPost = new HttpPost(oAuthMessage.URL);
  //Some Code
  HttpClient httpClient = new DefaultHttpClient();
  HttpResponse httpResponse = httpClient.execute(httpPost); ------1
  Integer code = httpResponse.getStatusLine().getStatusCode(); ---2
  return code;
}

现在我想嘲笑1号线和1号线。 2&返回一个模拟的HttpResponse&代码。

我试过这个却失败了:

@RunWith(MockitoJUnitRunner.class)
public class TestA {

//Spying some things here & Injecting them

@Test
public void testA() {

   HttpResponse httpResponse = Mockito.mock(HttpResponse.class, RETURNS_DEEP_STUBS);
   HttpClient httpClient = Mockito.mock(HttpClient.class);
   HttpPost httpPost = Mockito.mock(HttpPost.class);

   Mockito.doReturn(httpResponse).when(httpClient).execute(httpPost);
   Mockito.when(httpResponse.getStatusLine().getStatusCode()).thenReturn(anyInt());
   //call the method
}

但这不起作用。任何人都可以给我任何想法吗? 感谢。

0 个答案:

没有答案