0

So i'm trying to use mockito to mock a getMethod request/responce. However i am having some problems

@Mock
private HttpClient client;
private GetMethod method;

@InjectMocks
private WebserviceInterface webserviceInterface;

@Before
public void setUp() throws Exception {
    initMocks(this);
    setting up the a valid customer happens here

}


@Test
public void shouldReturnValidCustomerWithValidBarcode() throws Exception {
    // TODO: Mock out the ParcelService so that we can specify what JSON data is returned.
    // TODO: Create the Customer object that we expect
    // TODO: Call the method of module under test
    // TODO: assertThat(expected, is(theActualObject)

    when(client.executeMethod(any(HttpMethod.class))).thenReturn(200);

    String aValidCustomerJson = "JsonGoes Here";

    when(method.getResponseBodyAsString()).thenReturn(aValidCustomerJson);
   assertThat(webserviceInterface.parcelSearch("aValidBarcode"), is(aValidCustomer));


}

but im getting a null pointer exception and im not sure why:

java.lang.NullPointerException at com.springapp.mvc.WebserviceInterfaceTest.shouldReturnValidCustomerWithValidBarcode(WebserviceInterfaceTest.java:137)

Any help if aprriciated, Thanks

Carl
  • 548
  • 1
  • 4
  • 21
  • 2
    Shouldn't your `method` field be annotated `@Mock` too? – wjans Jul 24 '15 at 11:34
  • As an aside, (if possible), you may want to drop the initMocks() in favour or the MockitoJUnitRunner: http://stackoverflow.com/questions/10806345/runwithmockitojunitrunner-class-vs-mockitoannotations-initmocksthis – Alex Jul 24 '15 at 13:06
  • Are you able to add a comment to the line that is throwing the NPE? – Alex Jul 24 '15 at 13:07
  • Something that's messed me up in the past is if the method I'm mocking is overloaded, then it won't return the mocked method response, it will always just return null. Is this definitely not the problem? – Seb Jul 24 '15 at 13:37

1 Answers1

2

Generally speaking it is not suggested to mock external libraries because your test code will depend on them. Better to create an abstration layer and mock it. In you case you can wrap HttpClient in a class so you can easily stub its method.

Gualtiero Testa
  • 244
  • 1
  • 3
  • 8