2015-12-28 36 views
0

我目前正在测试akka应用程序。 我碰到过某种模式:我想测试一个TestProbe已经收到了某个消息,以某些字段为模。akka:测试邮件模数

例如,如果消息是:

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

然后,我可能要测试usernamescore如预期,但在收到什么时候该消息并不关心。

目前我想写点东西像这样:

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

怎么能测试探针类进行扩展,使这样的事情可能不是写的?

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

除了缩短我的代码,我希望这个问题的答案会进一步我对Scala编程语言的理解。

回答

0

我认为你不能做这样的事情

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

因为,首先最后一个属性(时间戳)是不是varval需要有值,如果你想要的是通过传递模式参数你不能'因为我们不能不通过模式没有所有case替代品(部分功能)。

所以UserInfo(用户名,得分, _)是一个对象,一个普通的实例。

但是,我们可以做一个解决方法,扩展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