测试Okhttp3响应主体-java.lang.IllegalStateException:request == null

时间:2019-05-28 12:33:02

标签: java mockito httprequest httpresponse okhttp3

我在类中有一个方法,该方法执行HTTP GET调用以获取响应对象并进一步利用该对象。伪代码如下:

public class ABC{
 public method abc1(){
  HttpUrl url = HttpUrl.parse("url").newBuilder()
    .addPathSegment("path1")
    .build();

  Request request = new Request.Builder().url(url).build();
  try (Response response = client.newCall(request).execute()) {
   ResponseBody responseBody = response.body();
   String body = responseBody.string();
   //other logic
  }catch (IOException e) {}

 }
}

现在,我正在编写一个单元测试以测试响应对象(json对象)中的不同值。如下:

public class ABCTest{
 @Mock
 private OkHttpClient mockHttpClient;
 @Mock
 private Call mockCall;

 @Before
 public void initMocks() {
  MockitoAnnotations.initMocks(this);
 }

 @Test
 public void abc1Test(){

  ResponseObjectInJson responseObjectInJson = new ResponseObjectInJson(); //this is a object from my POJO class that i create in order to be received as a response

  JSONObject jsonObject = new 
  JSONObject(responseObjectInJson);

  ResponseBody body = 
  ResponseBody.create(MediaType.parse("application/json"),new 
  Gson().toJson(jsonObject));

  Response.Builder builder = new Response.Builder();
  builder.code(200);
  Response response = builder.body(body).build();

  when(mockCall.execute()).thenReturn(response);
  when(mockHttpClient.newCall(any(Request.class))).thenReturn(mockCall);
  //call the abc1() method here to see the response and behaviour
 }
}

问题是,当我调试时,它会在构建响应builder.body(body).build();时引发InvocationTargetException。

并显示java.lang.IllegalStateException:request == null。我知道我需要在Response.Builder中设置请求,因为当我在调试器中评估表达式builder.body(body)时,结果将显示标头和正文,但request为null。

i.e., builder.request(//a request here)

我的问题是: 1.作为回应,为什么需要此请求? 2.如何设置?因为自决赛以来我一直无法嘲笑。

预先感谢

0 个答案:

没有答案