如何处理junit中的异常?

问题描述

我有这个方法,它是负面的测试用例,当某种文件不存在时它会失败,

@Test
    @displayName("Negative test Case when  tab doesnt exist,Expected Exception")
    public void tabDoesntExist() throws Exception {
        Data gs = new Data(propertyFile,outsourceFolder);
        Exception exception = assertThrows(Exception.class,() -> gs.processWorkbook(filelist));
        assertTrue(exception.getMessage().contains("null"));
    }

但截至目前该文件已存在,不会抛出任何异常,所以我们如何处理它,截至目前它提供了类似的东西,任何形式的帮助表示赞赏。

Expected java.lang.Exception to be thrown,but nothing was thrown.

junit.framework.AssertionFailedError: Expected java.lang.Exception to be thrown,but nothing was thrown.
at com.planlytx.aggrid.GenDropdownjsonTest.inputFileDoesntExist(GenDropdownjsonTest.java:93)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

解决方法

在您的测试中,您没有调用您正在测试的实际方法。因此不会抛出异常。

替换,

Exception exception = assertThrows(Exception.class,() -> gs.processWorkbook(filelist));

when(gs.processWorkbook(filelist)).thenThrow(new Exception());

更新: 如果您的方法在这种情况下返回 void,您可以使用以下语法。

doThrow(new Exception()).when(gs).processWorkbook(filelist);