Это способ проверить исключения, выданные внутри функции в JUnit? - PullRequest
0 голосов
/ 18 октября 2018

У меня есть этот код на 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;
}

1 Ответ

0 голосов
/ 19 октября 2018

Вы можете проверить, если выбрасывать исключения ... Пример, как вы можете сделать это

@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
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...