Carl
Carl

Reputation: 618

Getmethod Mokito java mock

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

Upvotes: 0

Views: 1399

Answers (1)

Gualtiero Testa
Gualtiero Testa

Reputation: 244

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.

Upvotes: 2

Related Questions