简体   繁体   English

Getmethod Mokito Java模拟

[英]Getmethod Mokito java mock

So i'm trying to use mockito to mock a getMethod request/responce. 所以我正在尝试使用Mockito模拟一个getMethod请求/响应。 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 如果有任何帮助,谢谢

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. 在这种情况下,您可以将HttpClient包装在一个类中,以便可以轻松地对其方法进行存根。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM