java - 它是一种测试 JUnit 函数内部抛出的异常的方法吗?

标签 java eclipse testing exception junit

我有这段 Java 代码,我想测试所有代码。我已经测试了除捕获异常的部分以外的所有部分。我已经搜索了一些但找不到任何东西,我知道我可以从函数中抛出异常,但如果可能的话我想把它们放在里面。

protected int[][] getJson(String fileName) {
    int[][] array = new int[NUMB_ROW][NUMB_COLUMN];

    try (BufferedReader buffer = new BufferedReader(
            new InputStreamReader(new FileInputStream(fileName), "UTF-8"))) {
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = buffer.readLine()) != null) {
            sb.append(line);
        }
        // Split string where there aren't a number
        String[] numbers = sb.toString().split("[^-?1-9]");
        int[] intNumbers = new int[NUMB_ROW * NUMB_COLUMN];
        int i = 0;

        // Remove empty spaces and put them in 1d array
        for (String number : numbers) {
            if (!number.equals("")) {
                intNumbers[i++] = Integer.parseInt(number);
            }
        }

        // Convert 1d array to 2d array
        int index = 0;
        for (int row = 0; row < NUMB_ROW; row++) {
            for (int col = 0; col < NUMB_COLUMN; col++) {
                array[row][col] = intNumbers[index++];
            }
        }

    } catch (FileNotFoundException e) {
        array = null;
        logger.log(Level.WARNING, String.format("File not found: %s%n", e.getMessage()));
    } catch (IOException e) {
        array = null;
        logger.log(Level.WARNING, String.format("IOException: %s%n", e.getMessage()));
    }

     return array;
}

最佳答案

你可以测试是否抛出异常... 如何执行此操作的示例

@Test(expected=IllegalFieldValueException.class)
public void functionOfYourTest() {
    // your code that thrown an exception
    // In this case we will test if will throw an exception
    // of the type IllegalFieldValueException
}

关于java - 它是一种测试 JUnit 函数内部抛出的异常的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52864495/

相关文章:

java - 使用setContentView时多次定义函数

java - Byte Buddy 和 ClassLoadingStrategy.UsingLookup

java - 如何将一个独立项目添加到另一个maven项目中

Eclipse (CDT) 项目默认值

java - Eclipse:主函数存在时出现 "selection does not contain a main type"错误

带有图标名称的 Java 2d 数组

Java InputStreamReader,mac 和 linux 上的输出不同

networking - 如何在 CoAP 一致性测试套件中对测试用例进行分组

json - grunt-mocha-test JSON 报告器到没有 console.logs 的文件

c# - 有限状态机与另一种在 C# 中进行 UI 测试的技术