gpt4 book ai didi

java - Getmethod Mokito java 模拟

转载 作者:行者123 更新时间:2023-12-02 04:29:53 26 4
gpt4 key购买 nike

所以我尝试使用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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com