使用assertEquals测试hasEnded时预期true却返回false问题排查
问题排查:assertEquals断言hasEnded为true但实际返回false
问题场景
使用assertEquals断言游戏类的hasEnded属性应为true,但测试结果返回false,报错信息:
AssertionFailedError: expected: "true" but was: "false"
相关核心代码如下:
游戏类定义
class Schwimmen( var hasEnded: Boolean = false )
回合推进方法
fun nextTurn() { val game = rootService.currentGame game.hasEnded= checkForEnd() }
结束条件判断方法
private fun checkForEnd(): Boolean { val game = rootService.currentGame return (game.cards.size < 3 && game.playerPassCounter >= game.players.size) || (game.activePlayer == game.endGamePlayer) }
测试方法
fun testNextTurn(){ testRootService.schwimmenService.startSchwimmen(players) testRootService.currentGame?.cards?.clear() testRootService.currentGame?.playerPassCounter = 5 assertEquals(true, testRootService.currentGame?.hasEnded) }
核心原因排查
未触发状态更新逻辑
hasEnded属性的赋值仅在nextTurn()方法中执行,测试代码只修改了cards和playerPassCounter,但没有调用nextTurn(),导致hasEnded始终保持初始默认值false。结束条件可能未满足
即使调用nextTurn(),需确认:game.players.size是否小于等于5:如果玩家数量大于5,playerPassCounter >= game.players.size条件不成立activePlayer == endGamePlayer是否为true:该分支也可能未触发,导致整个判断表达式返回false
修复建议
- 在测试中添加
nextTurn()调用,触发hasEnded状态更新:
fun testNextTurn(){ testRootService.schwimmenService.startSchwimmen(players) testRootService.currentGame?.cards?.clear() testRootService.currentGame?.playerPassCounter = 5 // 调用方法更新hasEnded状态 testRootService.schwimmenService.nextTurn() assertEquals(true, testRootService.currentGame?.hasEnded) }
- 验证
game.players.size的值,确保playerPassCounter = 5满足>= game.players.size;或调整测试数据,将playerPassCounter设置为与玩家数量一致的值。
内容的提问来源于stack exchange,提问作者Bahaa Kabaweh
相关产品推荐
相关产品推荐

