Creating http response as a return value for mockito

梦想与她 提交于 2019-12-07 17:30:33

Do you really need CarProvider to return a HttpResponse<Car[]>?

It feels like an aspect of the underlying comms (HttpResponse) might be leaking here. If the purpose of the CarProvider is to provide cars then perhaps it should be typed accordingly.

So, if you declared CarProvider as follows ...

public class CarProvider {
    // should perhaps consider List<Car> instead of Car[] here ...
    public Cars[] getCars(String carId, String carname) {
        HttpResponse<Car{}> response = Unirest.get(endpointUrl)
          .header("Accept", MediaType.APPLICATION_JSON)
          .queryString("carId",cardId)
          .queryString("carname",carname);

        return deserialise(response.getBody());
    }

    private Car[] deserialise(ResponseBody body) {
        // read the body and deserialise to Car[] 
    }
}

... then your test method would simplify to:

@Test
public void getCarsTest(){
    Mockito.when(carsUser.getCars(anyString(), anyString())).thenReturn(getDummyCarsList());

    // ...
}

private Cars[] getDummyCarsList(){
    return new Car{} {new Car(...), new Car(...)};
}

However, if this really is not possible and you really must mock HttpResponse<Car[]> then that'll look something like this:

HttpResponse<Car[]> mockedResponse = Mockito.mock(HttpResponse.class);
Mockito.when(mockedResponse.getCode()).thenReturn(200);
Mockito.when(mockedResponse.getBody()).thenReturn(someSerialisedFormOfYourCarArray);

Mockito.when(carsUser.getCars(anyString(), anyString())).thenReturn(mockedResponse);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!