2015-12-28 34 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