我有 java 语言的 TicTacToe 游戏,我必须为这个 Game 类做 Junit 测试用例,因为我需要为这个应用程序应用变异测试。谁能帮我写出好的测试用例。
public class Game {
private Board board;
private Queue<Player> players;
public Game() {
board = new Board();
players = new LinkedList<>();
addPlayers();
}
private void addPlayers() {
players.add(new Player("X"));
players.add(new Player("O"));
}
private void startGame() throws IOException {
do {
Player currentPlayer = players.remove();
System.out.println("Enter position for Player "+currentPlayer.toString());
java.io.BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
board.placeMarker(currentPlayer,new Position(Integer.parseInt(in.readLine()),Integer.parseInt(in.readLine())));
players.add(currentPlayer);
System.out.println(board.toString());
if(board.hasWon(currentPlayer)){
break;
}
}while (board.hasEmptyPosition());
}
public void main(String[] args) {
Game game= new Game();
try {
game.startGame();
} catch (IOException e) {
e.printStackTrace();
}
}
最佳答案
这是一个非常简单的应用程序,因此没有太多可能的测试要做。
首先你应该专注于测试类的公共(public) API,但在你的情况下你只有 main
。其次,您依赖于外部输入,这使得测试您的代码变得更加困难...
我建议您阅读一些有关如何使您的代码更易于测试的文章。例如:
- > https://medium.com/feedzaitech/writing-testable-code-b3201d4538eb
- > https://www.toptal.com/qa/how-to-write-testable-code-and-why-it-matters
一些开场白:
- 创建一个负责启动应用程序的类(具有 main 方法):我们将其称为类
Application
- Make Game
startGame()
方法接收一个返回输入的函数作为输入(在您的 PROD 代码中,您将使用 BufferedReader,在测试代码中,您可以使用例如流 addPlayers
方法的想法相同- 为每个播放提取一个方法(基本上是
do...while
中的代码)以便您也可以对其进行测试
也许你可以找到更多的任务
ps: 但最后,有了这样一个基本的代码库,这有点矫枉过正......
关于java - 如何用 JUnit 测试来测试这个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58360300/