2014-01-22 16 views

回答

6

硬編碼演員的路徑很可能讓你以後不開心,因此你應該採取測試的難度它作爲設計提示。我建議使用ActorRef作爲第一選擇,並且只有在無法工作的情況下返回到ActorPath,但通過告知參與者使用哪條路徑(在消息中或通過構造函數),可以保持其靈活性。

+1

我同意,雖然根據我的經驗,路徑作爲行動者之間的循環依賴關係的解決方案是有幫助的,而另一種情況是當您需要動態更改實現時(只需要殺死當前行爲者並在相同路徑下啓動新行爲者) –

5

我想出了一個非優雅的解決方案。
我定義了一個名爲「ForwardActor」

class ForwardActor(to: ActorRef) extends Actor { 
    def receive = { 
     case x => to.forward(x) 
    } 
} 

然後幫助演員在我的測試情況下

val probe = TestProbe() 
val system.actorOf(Props(new ForwardActor(probe.ref)), "myActor") 
probe.expectMsg(...) 
+0

我會等待其他答案,看看test-kit是否包含此用例的解決方案,而無需進行此類調整。 – Radian

+0

這是正確的做法。 – sourcedelica

+0

@羅蘭是正確的大多數人應該使用ActorRef可能有某些情況下,如果你在應用程序級別處理可靠性,你希望一個ActorSelection而不是做「消失並忘記」。在這種情況下,這種解決方案可以讓您從中獲得ActorPath或ActorSelection的轉發角色。 – simbo1905

2

假設你要測試的這款代碼:

def f(as: ActorSelection): Unit = as ! "msg" 

然後你可以使用TestProbeActorSelection

val p = TestProbe() 
val as = system.actorSelection(p.ref.path) 
f(as) 
p.expectMsg("msg") 
1

我還開發了一個小型圖書館/ DSL用於處理此類案件(其允許創建更復雜的層次結構,並偵聽某些路徑元素的消息)https://github.com/stanislav-chetvertkov/spy-tree。上述情況可以如下處理:

import com.github.spytree.ActorListenersDSL._ 

val myActorProbe = TestProbe() 
("myActor" replyTo myActorProbe.ref).materialize 

context.actorSelection("/user/myActor") ! "a message" 

val response = myActorProbe.expectResponse[String] 
response.message shouldBe "a message" 
相關問題