Getmethod Mokito java mock

时间:2015-07-24 11:29:10

标签: java unit-testing mocking mockito

所以我试图使用mockito来模拟getMethod请求/响应。但是我遇到了一些问题

@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));


}

但我得到一个空指针异常,我不知道为什么:

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

任何帮助,如果aprriciated,谢谢

1 个答案:

答案 0 :(得分:2)

一般来说,不建议模拟外部库,因为您的测试代码将依赖于它们。 最好创建一个abstration层并模拟它。 在你的情况下,你可以将HttpClient包装在一个类中,这样你就可以轻松地存根它的方法。