mardi 24 novembre 2020

Is it possible to initialize some of the fields in a mock object

I have a code that I cannot correctly cover with tests. I am using the Mockito library. And I had difficulty at the moment of starting the test.

Below is the test code:

@Test
public void testLoadCar() {
    when(remoteService.loadData()).thenReturn(new DataResult<DataCar>("", "", new DataCar()));
    when(dataResult.hasError()).thenReturn(true);
    when(dataResult.response.hasHeaders()).thenReturn(true);
    requestNetwork = new RequestNetwork(remoteService);
    Response<DataCar> response = requestNetwork.load(request);
}

These are objects in the test class: remoteService, dataResult, request.

I am concerned about the moment where I am trying to implement the when method:

when(dataResult.response.hasHeaders()).thenReturn(true);

I would like to know if such a recording will work. If it doesn't work, then how can we handle this moment:

protected Response createResponse(DataResult<T> dataResult) {
    if (dataResult.hasError()  || !dataResult.response.hasHeaders()) {
        return dataResult.getErrorMessage());
    } else {
        return Response.data(dataResult.value);
    }
}

This is a method on the system under test (SUT) that has a createResponse() method. This method contains a call to the mock method of the DataResult object. To implement dataResult.hasError () I got it:

when (dataResult.hasError ()). thenReturn (true);

Then with! DataResult.response.hasHeaders () I have a problem. Since I don't understand how to substitute the value I need.

Aucun commentaire:

Enregistrer un commentaire