閱讀248 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Akka TestKit測試包的使用


Akka TestKit測試包的使用

TestKit,測試類必須繼承幾個接口:

class SendingActor01Test extends TestKit(ActorSystem("testsystem")) //TestKit創建testsystem用於測試
  with WordSpecLike //可以用must,in等語句描述測試方法
  with MustMatchers //must描述assertion,比如"hello" must (contain("hello"))
  with StopSystemAfterAll { //保證所有測試結束後關閉system
"A Silent Actor" must { //測試的文本規範
 "change state when it receives a message, single threaded" in { //每個in內是具體的測試內容
 //Write the test, first fail
 fail("not implemented yet")
 }
 "change state when it receives a message, multi-threaded" in {
 //Write the test, first fail
 fail("not implemented yet")
 }
 }
}

這些接口幫我們實現初始化actor testsystem,testActor,測試結束清理.


測試環境分為:

  • 單線程
  • 多線程
  • 多JVM

單線程

這個環境下,我們一般是簡單的測試,使用TestActorRef允許我們直接訪問silentActor內部

    //單線程環境
    "A Silent Actor" must {
      "change internal state when it receives a message, single" in {
        import SilentActorProtocol._ 
        //actor是不能直接訪問的,所以使用TestActorRef允許我們直接訪問silentActor內部
        val silentActor = TestActorRef[SilentActor] 
        silentActor ! SilentMessage("whisper")
        //直接調用silentActor的內部狀態,也可以直接調用內部方法
        silentActor.underlyingActor.state must (contain("whisper")) 
      }
    }

TestActorRef和LocalActorRef,使用隻做測試用的CallingThreadDispatcher作為調度器,CallingThreadDispatcher不會在新線程中調用actor

多線程環境

由於不能直接訪問actor,我們隻能通過testActor獲取actor的message,比如:

    //多線程下測試,不能直接訪問actor內部,所以通過testActor做消息的中轉
    "A Silent Actor" must {
      "change internal state when it receives a message, multi" in {
        import SilentActorProtocol._ 
        val silentActor = system.actorOf(Props[SilentActor], "s3") 
        silentActor ! SilentMessage("whisper1")
        silentActor ! SilentMessage("whisper2")
        //silentActor將處理結果發送給testActor
        silentActor ! GetState(testActor) 
        //expectMsg方法獲取testActor收到的message
        expectMsg(Vector("whisper1", "whisper2")) 
      }

expectMsg,expectMsgPF方法接受來自test actor的消息。所以當要測試一個actor相應的message,可以將消息發送給testActor,testActor轉發到我們的測試方法。

多JVM環境

discuss on chapter 5


我們歸類一下actor,有如下三種:

1. SilentActor

不返回,不發送message。我們要測試它是否接受到了message,知否改變了內部狀態,是否拋出異常。
對於單線程環境,我們用TestActorRef就可以。多線程環境我們還是要用testActor。

2. SendingActor

會發送message給其他的actor,一般我們測試將其作為黑盒.使用testActor接受消息,並使用expectMsg或者expectMsgPF從testActor獲取從被測試actor收到的message。

3.SideEffectingActor

接受一個message,並與一些object交互。當我們發送message給它時,要檢測object是變動


TestProbe

TestKit提供了testActor,我們使用:

  • expectMsg
  • expectNoMsg
  • ignoreMsg
  • expectMsgPF

等方法來獲取testActor接受的message.如果我們要接受發送給多個actor的message,我們就要用TestProbe了,直接調用TestProbe()即可

總結

大多數情況下,使用testActor測試是最方便的。


最後更新:2017-04-03 05:39:44

  上一篇:go HDU2063-過山車
  下一篇:go Akka學習過程的疑問