2014-11-03 39 views
1

我是在akka系統上使用scala的新手。小孩在akka上的測試回覆

我有一位父母演員(名字叫「經理」),向孩子發送消息,並接收一個答案,並將答案轉發給下一個孩子。 最後的演員保存整個過程的結果。

我想創建一個將消息發送給父(「管理器」)的端到端測試,並期望來自最後一個接收結果的actor的消息。 我正在尋找一種簡單的方法來指導最終演員發送消息回測試。由於測試不是發件人,也不是簡單的演員,我不知道如何正確引導信息。

以下是測試代碼:

class EndToEndTest extends TestKit(ActorSystem("MyActorSystem")) 
with FunSuiteLike with Matchers with BeforeAndAfterAll with ImplicitSender { 

    override def afterAll { 
     TestKit.shutdownActorSystem(system) 
    } 

    test("should send result") { 

    val actor = system.actorOf(Props(new Manager(name = "ActorManager"))) 
    actor ! tPoint(1000L) 
    actor ! tPoint(2000L) 

    expectMsg(ActorResult(1)) 
    } 
} 

最後一個兒童演員和:

class SensorHealthReportMySqlActor extends Actor with ActorLogging { 

    def receive = { 
     case Result(result: Long) => 

     //this is where i would like to send the test a message with Result(result) 

     case _ => 
      log.error("Unknown message type") 
    } 

} 

任何幫助,將不勝感激。

回答

2

我認爲你想要的解決方案是通過一個ActorRef作爲消息中的參數,因此當消息應發送給除當前消息的發送者以外的某個參與者時,接收者知道應該發送答覆的位置。

因此就沿着這些線路:

import akka.actor.{Actor, Props, ActorRef, ActorLogging} 

case class tPoint(n: Long) 
case class Result(result: Long, replyTo: ActorRef) 
case class ActorResult(result: Long) 

class Manager(name: String) extends Actor { 

    val child = context.actorOf(Props(new SensorHealthReportMySqlActor)) 

    override def receive: Receive = { 
    case msg: tPoint ⇒ 
     child ! Result(msg.n, sender()) 
    } 
} 



class SensorHealthReportMySqlActor extends Actor with ActorLogging { 

    def receive = { 
    case Result(result: Long, replyTo: ActorRef) => 
     //this is where i would like to send the test a message with Result(result) 
     replyTo ! ActorResult(1) 

    case _ => 
     log.error("Unknown message type") 
    } 

} 

在這種情況下,sender()Managerreceive方法是測試本身,這是一個ImplicitSender(如你在測試中聲明)。這是一個可以接收消息的幕後創建的演員。

在非測試系統中,您可以使用ask模式或Inbox來達到同樣的目的。請參閱文檔Actors