首页 > 解决方案 > JUnit 问题/NullPointer 异常

问题描述

在我的代码中,我运行了一个 Junit 测试,两个 for 循环显示为黄色,表示 2 个分支中有 1 个丢失。并且循环中的代码存在空指针异常。我不明白这是什么问题,所以有人可以帮我吗?(添加更多 cus 主要是代码)

@Test
public void testTicTacToeBoard() {
    TicTacToeBoard board = new TicTacToeBoard();
    CellState[][] expectedBoard = {
            {CellState.EMPTY, CellState.EMPTY,CellState.EMPTY},
            {CellState.EMPTY,CellState.EMPTY,CellState.EMPTY},
            {CellState.EMPTY,CellState.EMPTY,CellState.EMPTY}
    };
    assertEquals(PlayerID.PLAYER_ONE, board.turn);
    assertTrue(array2Dequals(expectedBoard, board.board));
}

public enum PlayerID {
    PLAYER_ONE, PLAYER_TWO
}

public enum CellState {
    EMPTY(" "),
    PLAYER_ONE("X"),
    PLAYER_TWO("O");

    private final String icon;

    CellState(String icon){
        this.icon = icon;
    }

    @Override
    public String toString(){
        return this.icon;
    }
}

/**
 * Represent the game board as a 2D array of CellState. We use enum object
 * to ensure that only the three possible values are used.
 */
CellState[][] board;

/**
 * Represents whose turn it is to play the next time play(int,int) is
 * called. We use an enum object PlayerID to ensure only the two possible
 * values are used. We cannot use a CellState object as the value EMPTY is
 * not a valid value for a player. Therefore we use another enum type.
 */
PlayerID turn;

/**
 * The constructor must initialise board to a 3x3 2D array fill with the
 * value CellState.EMPTY. In addition the turn should be initialised to the
 * first player to play, i.e. PlayerID.PLAYER_ONE.
 */
public TicTacToeBoard() {
    this.turn = PlayerID.PLAYER_ONE;
    for(int i = 0; i < 3; i++) {
        for(int j = 0; j < 3; j++) {
            this.board[i][j] = CellState.EMPTY;
        }
    }           
}

标签: javapointersjunitnull

解决方案


推荐阅读