简体   繁体   English

Junit没有捕获文件未找到异常

[英]Junit isn't catching file not found exception

@Test(expected=FileNotFoundException.class)
public void downloadExcelTest() {
    stub(mockRoomService.getRoomByCode("ICU5")).toReturn(ICU5);
    stub(mockRS.makeExcel(anyInt(), any(Room.class))).toReturn("FILE_DOES_NOT_EXIST.xls");
    rc.downloadExcel(mockHTTP, 1, "ICU5", mockM);
}

So I'm trying to make a junit test to check for an exception, but it doesn't seem to be catching the exception. 所以我正在尝试进行junit测试以检查异常,但它似乎没有捕获异常。 When I run the test, it says the expected exception did not occur, yet the following error is in the console. 当我运行测试时,它表示没有发生预期的异常,但控制台中出现以下错误。

java.io.FileNotFoundException: FILE_DOES_NOT_EXIST.xls (The system cannot find the file specified)

Is my syntax wrong or is it something else? 我的语法错了还是别的什么?

Junit won't detect the exception if it is caught within the method. 如果在方法中捕获异常,Junit将不会检测到异常。 You need to either throw the exception from downloadExcel, or find another way to notify the calling method of the error. 您需要从downloadExcel中抛出异常,或者找到另一种方法来通知调用方法错误。

public void downloadExcel() throws IOException {
    try{
        ...
    }
    catch (NullPointerException e) { 
        throw new NullPointerException("Null exception"); 
    }
}

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

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