akka Scala测试,如何从参与者获取结果

ctzwtxfj  于 2022-11-06  发布在  Scala
关注(0)|答案(1)|浏览(169)

我遇到了一个问题。我正在尝试做一些scala测试。我的问题是我不知道如何获取一个方法的return来测试它是否返回一个序列给我。我该怎么做呢?我的Test类是:(有效)

"The game actor" should {

    "accept a specific numbers of players and notify that the game is started with an initial state" in {
      val gameActor = TestActorRef[GameMatchActor](GameMatchActor.props(NUMBER_OF_PLAYERS))
      val player1 = TestProbe()
      val player2 = TestProbe()

      gameActor ! GamePlayers(Seq(GamePlayer("id1", "player1", player1.ref), GamePlayer("id2", "player2", player2.ref)))
      player1.expectMsgType[MatchFound]
      player1.send(gameActor, PlayerReadyServer("id1", player1.ref))
      player2.expectMsgType[MatchFound]
      player2.send(gameActor, PlayerReadyServer("id2", player2.ref))

      player1.expectMsgType[GamePlayersClient]
      player2.expectMsgType[GamePlayersClient]

    }
  }

返回给我GamePlayersClient的方法是:

private def defineRoles(players: Seq[GamePlayer]): Seq[Player] = {
    var playersRole: Seq[Player] = Seq()
    val rand1 = Random.nextInt(players.length)
    val rand2 = Random.nextInt(players.length)

    for (n <- 0 until players.length) {
      n match {
        case n if n == rand1 || n == rand2 =>
          playersRole = playersRole :+ Impostor(players(n).id, players(n).username, Point2D(0,0))
        case _ => playersRole = playersRole :+ Crewmate(players(n).id, players(n).username, Point2D(0,0))
      }
    }
    playersRole
  }

还有:

// watch the players with the new actor ref
    val playersRole = defineRoles(players)
    this.players.foreach(p => {
      p.actorRef ! GamePlayersClient(playersRole)
      context.watch(p.actorRef)
    })

所以,我怎么才能把GamePlayersClient(playersRole)和搜索如果里面有一个序列的球员,其中一个是“船员”。谢谢

koaltpgm

koaltpgm1#

您可以在TestProbe上使用receive ...方法之一收集发送到探测器的GamePlayersClient消息,然后使用ScalaTest的匹配器Assert有关这些消息的内容。
例如,您可以将

player1.expectMsgType[GamePlayersClient]

val gpcMessageOpt1: Option[GamePlayersClient] = Option(player1.receiveN(1)).flatMap {
  case g: GamePlayersClient => Some(g)
  case _ => None
}

gpcMessageOpt1 shouldNot be(empty) // effectively the same as the expectMessage

如果感兴趣的字段是playersRole,则可能有

// To my mind, it's generally OK to do unsafe things like get in a test...
gpcMessageOpt1.get.playersRole shouldNot be(empty)

相关问题