java - Getmethod Mokito java 模拟

标签 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)

如果有任何帮助,谢谢

最佳答案

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

关于java - Getmethod Mokito java 模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31609412/

相关文章:

java - JSON Jackson - 使用自定义序列化程序序列化多态类时出现异常

java - @AttributeOverride 是什么意思?

c# - 无法测试的 Braintree API : Should I alter the source code or individually wrap every class?

c - Google Test C 中的调试、系统函数(fopen、fclose、fread、fwrite、...)和 for 循环

node.js - nodejs - 模拟模块,天真的方法

iphone - OCUnit 和 OCMock 在 iPhone SDK 上工作吗?

java - 序列化-为什么readObject不能读取整个文件?

java - 如何从 android TextView 中 Intent (发送到其他 Activity )字符串的一部分?

javascript - 使用 Jest/Enzyme 检查咏叹调

ios - 无法使用mockURLSession调用非函数类型 'URLSession'错误的值