shashwat
shashwat

Reputation: 23

Cover EXCEPTION in the catch block while using mockito

Function to be tested:

public void deleteFile(File file)  {
            
            try {
                Files.delete(file.toPath()) ;
                    
                log.info("Csv file deleted from system succesfully after processing the data");
                    
                
            } catch (IOException e) {
                // TODO Auto-generated catch block
                
            }           
}

Test code:

@Test
void testExceptionDuringDeletingFile() {
          
      helper=mock(Helper.class);
      
     
      //String bucket ="bucket"; 
      //String key = "key"; 
      File file = new File("");
      
      doThrow(IOException.class).when(helper).deleteFile(file);
      
      Assertions.assertThrows(IOException.class,()->helper.deleteFile(file));
}

But I am getting the following exception:

org.mockito.exceptions.base.MockitoException: Checked exception is invalid for this method! Invalid: java.io.IOException at com.lululemon.product.ap.reprocess.producer.HelperTests.testExceptionDuringDeletingFile(HelperTests.java:191) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at

Upvotes: 1

Views: 3263

Answers (1)

iambk
iambk

Reputation: 334

Because your deleteFile() method doesn't throw the IOException. You catch it in your method implementation and do something with it.

And, your mocked Helper class instance really can't throw IOException from the deleteFile() method because the real deleteFile() method doesn't.

Throw the IOException from your method and you won't get the error.

deleteFile method:

public void deleteFile(File file) throws IOException {
    try {
        Files.delete(file.toPath());
        log.info("Csv file deleted from system successfully after processing the data");
    } catch (IOException e) {
        throw new IOException("Couldn't delete file. Try again!");
    }
}

Test method:

@Test
void testExceptionDuringDeletingFile() throws IOException {
    File file = new File("");
        
    Helper helper = mock(Helper.class);
    doThrow(IOException.class).when(helper).deleteFile(file);

    Assertions.assertThrows(IOException.class, () -> helper.deleteFile(file));
}

Upvotes: 1

Related Questions