我在Java中有这段代码,我想测试所有代码。除具有catch异常的部分外,我已经测试了所有其他内容。我已经搜索了一些,却找不到任何东西,我知道我可以从函数中抛出异常,但是我想尽可能地将它们放入内部。
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;
}
答案 0 :(得分:4)
您可以测试是否抛出异常... 一个如何执行此操作的示例
@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
}