From 01f94e31986ea171edd8ccd5dac7ffadc4ebc8d0 Mon Sep 17 00:00:00 2001 From: Tobias Krause Date: Mon, 31 Jan 2022 15:40:17 +0100 Subject: [PATCH] tictactoe: countCharsInDiag throws IndexOutOfBoundsException for invalid index --- src/main/java/de/tims/tictactoe/ai/AIHard.java | 6 +++++- src/test/java/de/tims/tictactoe/ai/AIHardTest.java | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/main/java/de/tims/tictactoe/ai/AIHard.java b/src/main/java/de/tims/tictactoe/ai/AIHard.java index 6ea1d35..3e802c2 100644 --- a/src/main/java/de/tims/tictactoe/ai/AIHard.java +++ b/src/main/java/de/tims/tictactoe/ai/AIHard.java @@ -78,7 +78,11 @@ public class AIHard implements TicTacToeAI { return count; } - public int countCharsInDiag(int index, char charToCount) { + public int countCharsInDiag(int index, char charToCount) throws IndexOutOfBoundsException { + if (index < 0 || index > 1) { + throw new IndexOutOfBoundsException("Only 0 and 1 are allowed values for index!"); + } + int count = 0; char[][] board = gl.getBoard(); diff --git a/src/test/java/de/tims/tictactoe/ai/AIHardTest.java b/src/test/java/de/tims/tictactoe/ai/AIHardTest.java index d04e720..72934b6 100644 --- a/src/test/java/de/tims/tictactoe/ai/AIHardTest.java +++ b/src/test/java/de/tims/tictactoe/ai/AIHardTest.java @@ -125,5 +125,17 @@ class AIHardTest { new char[][] { {'-', '-', 'o'}, {'o', 'o', '-'}, {'-', '-', '-'} }, 1, 'o', 2)); } + + @Test + void invalidIndexCausesIndexOutOfBoundsException() { + int index = 2; + char charToCount = 'o'; + String msg = "Only 0 and 1 are allowed values for index!"; + doReturn(new char[][] { {'-', '-', '-'}, {'-', '-', '-'}, {'-', '-', '-'} }).when(gl).getBoard(); + + AIHard ai = new AIHard(gl); + + assertThatThrownBy(() -> {ai.countCharsInDiag(index, charToCount);}).isInstanceOf(IndexOutOfBoundsException.class).hasMessage(msg); + } }