lundi 25 juillet 2016

How to Mock a constructor using Mockito

I have a class like this:

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;
}

Now I want to mock the line 1 & 2 & return a mock HttpResponse & code.

I have tried this but failed:

@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
}

But this is not working. Can anyone give me any idea please? Thanks.

Aucun commentaire:

Enregistrer un commentaire