简体   繁体   English

Mockito 在 void 方法中捕获异常

[英]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.我已经尝试了很多次,但我无法用 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我总是这个错误:[错误]失败:[错误] JUnit.mockException 预期异常:java.lang.Exception

and lines are not covered by test.并且线路不被测试覆盖。

Firstly, your method deleteTableEsiti() never throws any exception.首先,您的方法deleteTableEsiti()永远不会引发任何异常。 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).无论如何,您的单元测试实际上并没有调用模拟方法deleteTableEsiti() ,因为它所做的只是设置一个模拟规则以在调用该方法时抛出异常(您从不调用)。

So, after calling Mockito.when , you should call (or do something that calls) that method in your unit test.因此,在调用Mockito.when之后,您应该在单元测试中调用(或执行调用)该方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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