简体   繁体   中英

Mocking a mothod that is being called multiple times in java

I want to test one method which is calling another method multiple times.

Class Sample{
    OtherClass otherClass;
    public OutputPoJo callABCMultipleTImes(){
        OutputPoJo outputPojo;
        try{
            outputPojo = otherClass.callABC();
        } catch(RuntimeException ex){
           //Retrying call one more time
           outputPojo = otherClass.callABC();
        }
        return outputPojo;
    }
}

I want to test this method. For that, I am doing something like this and that is working fine for me for different combination.

public void testCallABCMultipleTImes(){
   when(otherClass.callABC())
   .thenThrow(new RuntimeException("First try failed.")).
   .thenReturn(new OutputPOJO());
   mockedSampleClass.callABCMultipleTImes();
   Mockito.verify(otherClass,Mockito.times(2)).callABC();
}

Basically, I am checking that I got exception first time and second time, I got successful response. I am checking this by verifying that method is being called twice.

Is that the correct way to test this kind of scenario or is there any other way?

Thanks!

You should test that your method has the right behaviour, ie that it returns the value you expect it to return:

public void testCallABCMultipleTImes(){
   OutputPOJO value  = new OutputPOJO();
   when(otherClass.callABC())
     .thenThrow(new RuntimeException("First try failed."))
     .thenReturn(value);
   assertEquals(value, mockedSampleClass.callABCMultipleTImes());
}

In theory there's no need to call verify , because the fact that your method returned the correct value proves that it did the right thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM