简体   繁体   中英

Mockito catch exception in void method

I have this method:

public void deleteTableEsiti() throws Exception {
        try{
            EsitiDAO esitiDAO =  new EsitiDAO();
            int deletedEsiti = esitiDAO.deleteTableEsiti(em);
            
        }
        catch(Exception e ){
            log.error(e);
        }
        finally{
            em.close();
        }
    }

I'm trying to make the test that cover the catch exception. I have tried many times but I can't cover that lines with Mockito.

This is the test that i have write:

@Test(expected=Exception.class)
    public void mockException(){
        ServiceG service = Mockito.mock(ServiceG.class);
         try {
            Mockito.doThrow(Exception.class).when(service).deleteTableEsiti();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        };
        //Mockito.when(service.deleteTableEsiti()).thenThrow(new Exception());
    }

I have always this error: [ERROR] Failures: [ERROR] JUnit.mockException Expected exception: java.lang.Exception

and lines are not covered by test.

Firstly, your method deleteTableEsiti() never throws any exception. It catches it and logs it, but always returns normally. If you want your method to throw an exception, don't catch it, or catch it and throw a custom exception that wraps the original exception.

Your unit test does not actually call the mocked method deleteTableEsiti() anyway, since all it does is set up a mock rule to throw an exception when the method is called (which you never call).

So, after calling Mockito.when , you should call (or do something that calls) that method in your unit test.

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