Scala 测试,如何从演员那里获取结果

Scala Test, how to take a result from an actor

我有一个问题。我正在尝试做一些 Scala 测试。我的问题是我不知道如何使用方法的 return 来测试它是否 return 对我来说是一个序列。我该怎么做? 我的测试 class 是:(有效)

"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]

    }
  }

而 return 我 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) 并搜索里面是否有玩家序列并且其中一个是“Crewmate”。谢谢

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

例如,您可以替换

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)