【发布时间】:2018-01-29 11:14:01
【问题描述】:
我是 Mockito 的初学者。我有一个想要模拟的 HTTP get 调用。
需要测试的Utility文件是这个。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class GoogleAccessor {
private HttpClient client ;
public void getGoogle() throws ClientProtocolException, IOException {
String url = "http://www.google.com/search?q=httpClient";
client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result);
} catch (Exception e) {
System.out.println(e);
}
}
}
这是我的 jUnit 测试
import static org.mockito.Mockito.when;
import org.apache.http.ProtocolVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicStatusLine;
import org.mockito.Mock;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
public class TestTest {
@Mock
private HttpClient mClient;
@InjectMocks
private GoogleAccessor dummy;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testAddCustomer_returnsNewCustomer() throws Exception {
when(mClient.execute(Mockito.any())).thenReturn(buildResponse(201, "OK", "{\"message\":\"Model was stored\"}"));
dummy.getGoogle();
}
BasicHttpResponse buildResponse(int statusCode, String reason, String body) {
BasicHttpResponse response = new BasicHttpResponse(
new BasicStatusLine(new ProtocolVersion("HTTP", 1, 0), statusCode, reason));
if (body != null) {
response.setEntity(new ByteArrayEntity(body.getBytes()));
}
return response;
}
}
因为,mclient 没有启动,我一直收到这个错误
java.lang.NullPointerException
at com.amazon.cartographertests.accessors.TestTest.testAddCustomer_returnsNewCustomer(TestTest.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
...
UPDATE1:我已从 @glytching 合并 cmets 并删除了 setup() 中的变量初始化 我已经合并了来自@Maciej Kowalski 的 cmets,并使客户端成为 Utility 类中的类变量
更新 2:
解析到正确的import -> import org.mockito.Mock后NPE错误已解决;
但是,看不到mocked response的问题依然存在
【问题讨论】:
-
@InjectMocks是纯粹的魔法邪恶。使用良好的旧构造函数传递依赖项。
标签: java unit-testing junit mockito