测试随机失败

Tests randomly fails

本文关键字:失败 随机 测试      更新时间:2023-10-16

我正在写棋盘游戏,我需要以下功能:玩家掷两个骰子,如果他掷出双骰子(两个骰子上的数字相同(,他可以再次掷骰子,如果他再次掷出双骰子,他就会入狱。

在我的Game课上,它看起来像那样

void logic::Game::rollTheDice() {
    m_throwsInCurrentTurn++; 
    int firstThrow = m_firstDice.roll();
    int secondThrow = m_secondDice.roll();
    m_totalRollResult += firstThrow + secondThrow;
    if (firstThrow == secondThrow) m_doublesInCurrentTurn++;
}
std::string logic::Game::checkForDoubles() {
    std::string message;
        if (m_doublesInCurrentTurn == 0 && m_throwsInCurrentTurn == 1) {
            m_canThrow = false;
            m_canMove = true;           
        }
        if (m_doublesInCurrentTurn == 1 && m_throwsInCurrentTurn == 1) {
            message = "Doubles! Roll again.";           
            m_canThrow = true;
            m_canMove = false;
        }
        if (m_doublesInCurrentTurn == 1 && m_throwsInCurrentTurn == 2) {            
            m_canThrow = false;
            m_canMove = true;
        }
        if (m_doublesInCurrentTurn == 2 && m_throwsInCurrentTurn == 2) {
            message = "Doubles again! You are going to jail.";
            m_canThrow = false;
            m_canMove = false;
            getActivePlayer().lockInJail();
        }
        return message;
    }
void logic::Game::setInMotion(unsigned number) {
    m_players[m_activePlayer].startMoving(); 
    m_players[m_activePlayer].incrementPosition(number);
}

m_canThrow基本上启用或禁用单击"掷骰子"按钮的功能,m_canMove决定玩家令牌是否可以开始移动,m_players[m_activePlayer] std::vector<Player>startMoving()这样做,

void logic::Player::startMoving() {
    m_isMoving = true;
} 

令牌移动需要,因此在这里无关紧要。

我需要向您展示Game类中的最后一个函数是 reset(),主要用于测试目的

void logic::Game::reset() {
    m_throwsInCurrentTurn = 0;
    m_doublesInCurrentTurn = 0;
    m_totalRollResult = 0;
}

现在,单元测试有时会出错。有时,我的意思是完全随机,例如 10-20 次中有 1 次。

//first throw is double, second throw is not
TEST_F(GameTestSuite, shouldFinishAfterSecondRollAndMove) {
    auto game = m_sut.get();
    do {
        if (game.getThrowsInCurrentTurn() == 2) game.reset();
        game.rollTheDice();
        game.checkForDoubles();
        if (game.getThrowsInCurrentTurn() == 1 && game.getDoublesInCurrentTurn() == 1) {
            ASSERT_EQ(game.canThrow(), true);
            ASSERT_EQ(game.canMove(), false);           
        }
    } while (game.getThrowsInCurrentTurn() != 2 && game.getDoublesInCurrentTurn() != 1);
    ASSERT_EQ(game.canThrow(), false);
    ASSERT_EQ(game.canMove(), true);
    game.setInMotion(game.getTotalRollResult());
    ASSERT_EQ(game.getActivePlayer().isMoving(), true);
    ASSERT_EQ(game.getActivePlayer().getPosition(), game.getTotalRollResult());
}

正是这条线,ASSERT_EQ(game.canThrow(), false);有时等于do-while循环之后true,一旦m_canThrow设置为false

不应该:

} while (game.getThrowsInCurrentTurn() != 2 && game.getDoublesInCurrentTurn() != 1);

} while (game.getThrowsInCurrentTurn() != 2 && game.getDoublesInCurrentTurn() <= 1);

您希望最多允许两圈,但 0 或 1 双倍。