【发布时间】:2015-07-24 11:29:09
【问题描述】:
所以我正在尝试使用 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)
如有任何帮助,谢谢
【问题讨论】:
-
你的
method字段不应该也注释@Mock吗? -
顺便说一句,(如果可能的话),您可能希望放弃 initMocks() 或 MockitoJUnitRunner:stackoverflow.com/questions/10806345/…
-
你能在抛出 NPE 的行中添加注释吗?
-
过去让我感到困惑的是,如果我正在模拟的方法被重载,那么它不会返回模拟的方法响应,它总是只会返回 null。这绝对不是问题吗?
标签: java unit-testing mocking mockito