Funrab
Funrab

Reputation: 83

How to mock a method with a return value if there is a void method inside this method

I am testing a class that has a testable method (the method itself below) with a return value. Using Mockito I am having a problem. Problem with void method roomDao.updateData(outData);

public IEntity getData(SimBasket<DataEntity, SimRequest> request) {
    Entity outData = converterData.convertNetToDatabase(request);
    roomDao.updateData(outData);
    return outData;
}

Here is my test code:

@Test
public void getData() {
    simRepo = new SimRepo();
    Mockito.when(simRepo.getData(request)).thenReturn(new Entity());
}

Error log:

org.mockito.exceptions.misusing.CannotStubVoidMethodWithReturnValue: 'updateData' is a void method and it cannot be stubbed with a return value! Voids are usually stubbed with Throwables: doThrow(exception).when(mock).someVoidMethod();

I don't seem to really understand how to fix this, since the void method is inside a method with a return value.

Upvotes: 1

Views: 1450

Answers (1)

MD Ruhul Amin
MD Ruhul Amin

Reputation: 4502

instead of new SimRepo() try mock it by using Mockito's mock method:

@Test
public void getData() {
    SimRepo simRepo =Mockito.mock(SimRepo.class);
    Mockito.when(simRepo.getData(request)).thenReturn(new Entity());
}

Update: If you also want to count the number of times this mock method called use this:

// this will check if mock method getData() with parameter `request` called exactly 1 times or not.

Mockito.verify(simRepo, Mockito.times(1)).getData(request);

Upvotes: 2

Related Questions