【问题标题】:akka: test for a message modulo some fieldsakka:以某些字段为模测试消息
【发布时间】:2015-12-28 19:56:23
【问题描述】:

我目前正在测试一个 akka 应用程序。 我遇到了某种模式:我想测试TestProbe 是否收到了某个消息,以某些字段为模。

例如,如果消息是:

UserInfo(username: String, score: Int, timestamp: String)

然后我可能想测试usernamescore 是否符合预期,但不在乎何时收到消息。

目前我想写这样的东西:

testProbe.expectMsgPF() {
  case UserInfo(`username`, `score`, _) =>
}

如何扩展测试探针类,以便编写类似的东西?

testProbe.expectApproxMsg(UserInfo(`username`, `score`, _))

除了缩短我的代码之外,我希望这个问题的答案能加深我对 Scala 编程语言的理解。

【问题讨论】:

    标签: scala unit-testing akka akka-testkit testkit


    【解决方案1】:

    我认为你不能这样做

    testProbe.expectApproxMsg(UserInfo(`username`, `score`, _))
    

    因为,第一个最后一个属性(时间戳)不是 varval 需要具有值,如果您想要通过参数传递模式,您也不能,因为我们不能传递模式独自一人,没有所有case 替代品(PartialFunction)。

    所以UserInfo(username,score, _) 是一个对象,一个普通的实例。

    但是我们可以做一个解决方法,扩展TestProbe 类并将默认值添加到最后一个 UserInfo 的属性类。

    看看下面的,也许对你有用:

    HelloSpec.scala

    import org.scalatest._
    import scala.concurrent.duration._
    import akka.testkit._
    import akka.testkit._
    import akka.actor._
    
    
    case class UserInfo(username: String, score: Int, timestamp: String = "")
    
    case class MyTestProbe(_application: ActorSystem) extends TestProbe(_application) {
            def expectApproxMsg(max: Duration = Duration.Undefined, us:UserInfo):UserInfo = {
                    val obj = receiveOne(max).asInstanceOf[UserInfo]
                    assert(obj ne null, s"timeout ($max) during expectMsg while waiting for $us")
                    val expect = us.username == obj.username && us.score == obj.score
                    assert(expect, s"expected $us, found $obj")
                    obj
            }
    }
    
    class HelloSpec extends FlatSpec with Matchers with TestKitBase {
     implicit lazy val system = ActorSystem()
      "TestProbe actor" should "receive correct message" in {
    
            val probe2 = MyTestProbe(system)
            probe2.ref ! UserInfo("Salc2",9999,"whatever")
            probe2.expectApproxMsg(500 millis, UserInfo("Salc2",9999))
    
      }
    }
    

    Source code of Testkit

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-29
      • 1970-01-01
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 2013-05-25
      相关资源
      最近更新 更多