【问题标题】:Scala Test, how to take a result from an actorScala 测试,如何从演员那里获取结果
【发布时间】:2021-05-19 12:20:15
【问题描述】:

我有问题。我正在尝试做一些 scala 测试。我的问题是我不知道如何返回一个方法来测试它是否返回一个序列给我。我该怎么做? 我的测试课程是:(有效)

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

【问题讨论】:

    标签: scala akka scalatest


    【解决方案1】:

    您可以使用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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-03
      • 2023-04-06
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多