[英]how to test this class with JUnit testing?
I have TicTacToe game in java language and I have to do Junit test cases for this Game class, because I need to apply mutation testing for this application.我有 java 语言的井字游戏,我必须为此游戏 class 进行 Junit 测试用例,因为我需要为此应用程序应用突变测试。 can anyone help me to write good test cases.谁能帮我写出好的测试用例。
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();
}
}
} }
this is a very simple application, so there aren't a lot of possible tests to do.这是一个非常简单的应用程序,因此没有太多可能的测试要做。
first you should focus on testing the public API of a class, but in your case you only have main
.首先,您应该专注于测试 class 的公共 API,但在您的情况下,您只有main
。 Secondly, you depend on external input, which makes it harder to test your code...其次,你依赖于外部输入,这使得测试你的代码变得更加困难......
I recommend you to read some articles on how to make your code more testable.我建议您阅读一些有关如何使您的代码更可测试的文章。 For instance:例如:
A few starters:一些首发:
Application
创建一个 class 负责启动应用程序(具有 main 方法):我们称之为 class Application
startGame()
method receive as input a function that returns the input (in your PROD code you'll use the BufferedReader, in test code you could use a stream for instance使 Game startGame()
方法接收 function 作为输入,该 function 返回输入(在您的 PROD 代码中,您将使用 BufferedReader,在测试代码中您可以使用 stream 例如addPlayers
method addPlayers
方法的想法相同do...while
) so that you can test it as well为每次播放提取一个方法(基本上是do...while
中的代码),以便您也可以对其进行测试and maybe you can find a few more tasks也许你可以找到更多的任务
ps: but in the end, with such a basic codebase, this is kinda overkill... ps:但最后,有了这样一个基本的代码库,这有点矫枉过正......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.