我正在嘗試制作井字游戲類并對所有方法進行單元測驗。現在,我的類檔案如下所示:
public class TicTacToe {
public static final Character PLAYER_1 = 'X';
public static final Character PLAYER_2 = 'O';
public static final Integer BOARD_SIZE = 3;
private char[][] board;
private char currentPlayer;
public TicTacToe() {
board = new char[BOARD_SIZE][BOARD_SIZE];
initializeBoard();
currentPlayer = PLAYER_1;
}
public void initializeBoard() {
for(char[] row: board) {
Arrays.fill(row, '-');
}
}
public void printBoard() {
for(int i = 0; i < BOARD_SIZE; i ) {
for(int j = 0; j < BOARD_SIZE; j ) {
System.out.print(board[i][j]);
if(j == BOARD_SIZE - 1) {
System.out.println();
}
else {
System.out.print(" ,");
}
}
}
}
public boolean makeMove(int x, int y) {
if(x >= BOARD_SIZE || y >= BOARD_SIZE || x < 0 || y < 0 || board[x][y] != '-') {
return false;
}
board[x][y] = currentPlayer;
currentPlayer = currentPlayer == PLAYER_1 ? PLAYER_2 : PLAYER_1;
return true;
}
// more methods are below
}
如果我想在整個板子裝滿時測驗 printBoard() 是否作業,我將如何在不呼叫 makeMove() 或公開所有類變數的情況下做到這一點?
目前,我的測驗檔案如下所示:
import org.junit.*;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.*;
import static org.junit.jupiter.api.Assertions.*;
class TicTacToeTest {
private final PrintStream standardOut = System.out;
private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream();
@BeforeEach
public void setUp() {
System.setOut(new PrintStream(outputStreamCaptor));
}
@org.junit.jupiter.api.Test
@AfterEach
public void tearDown() {
System.setOut(standardOut);
}
@Test
void initializeBoard() {
}
@Test
void printBoard() {
TicTacToe game = new TicTacToe();
game.printBoard();
assertEquals("- ,- ,-\r\n- ,- ,-\r\n- ,- ,-", outputStreamCaptor.toString()
.trim());
// I want to test that a full board works for printBoard() right here.
}
// more testing methods below
}
我看到了一些關于在 Manifold 中使用 @Jailbreak 的資訊,但我無法讓它作業。如果它對任何人有幫助,我正在使用 IntelliJ。謝謝你的任何幫助!
uj5u.com熱心網友回復:
三個可選選項(還有更多):
- 創建 TicTacToe 的第二個建構式,您可以在其中傳遞到預填充板
public TicTacToe(char[][] board) - 添加一個額外的方法
public void loadBoard(char[][] board)。 - 使用反射來填充板變數。(糟糕的選擇,因為這可能導致另一種狀態)
- 添加一個包私有建構式,讓兩個類駐留在同一個包中。
- 創建包私有 setBoard 方法并在代碼的排列部分訪問它。
你也可以用區域模擬做一些事情,但我認為在這種情況下這也不是一個好的選擇。
另一個不錯的選擇是創建一個單獨的類來列印板:
public class BoardPrinter {
public BoardPrinter() {}
public printBoard(char[][] board} {
// print the board
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/337297.html
