2016-12-27 78 views
0

我有一位演員,其唯一的責任是將從外部接口(命令行,用戶等)收到的消息轉發到適當的主題。我想測試它是否正確發佈這些消息。如何測試發佈者到Akka集羣中的DistributedPubSub?

我將需要創建一些虛擬用戶,他們會期望發佈到某個主題的消息並對其收到的消息作出斷言。

這裏是我的代碼,我試圖認識到:

Messages.scala

case class Foo(foo: String) 

InterfaceForwardingActor.scala

import akka.actor.{Actor, ActorLogging} 
import akka.cluster.pubsub.{DistributedPubSub, DistributedPubSubMediator} 
import com.typesafe.config.Config 

/** Actor responsible for forwarding stimuli external to the system. 
    * For instance, messages from the command-line interface or from a UI. 
    * 
    */ 
class InterfaceForwardingActor extends Actor with ActorLogging { 
    import DistributedPubSubMediator.Publish 

    protected val mediator = DistributedPubSub(context.system).mediator 

    log.info(s"Hello from interface forwarder.") 

    final val topic = "info" 

    def receive = { 
    case foo: Foo => { 
     log.info("Forwarding a Foo message") 
     mediator ! Publish(topic, foo) 
    } 
    } 
} 

和測試代碼

InterfaceForwardingActorTest.scala

import akka.actor.{ActorSystem, Props} 
import akka.cluster.client.ClusterClient.Publish 
import akka.cluster.pubsub.DistributedPubSub 
import akka.testkit.{ImplicitSender, TestKit, TestProbe} 
import com.typesafe.config.ConfigFactory 
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike} 

class InterfaceForwardingActorTest extends 
    TestKit(ActorSystem("InterfaceForwardingActorSpec")) with ImplicitSender with 
    WordSpecLike with Matchers with BeforeAndAfterAll { 

    override def afterAll { 
    TestKit.shutdownActorSystem(system) 
    } 

    "An InterfaceForwardingActor" must { 
    val interfaceForwardingActor = system.actorOf(Props[InterfaceForwardingActor]) 

    val probe = TestProbe() 
    val mediator = DistributedPubSub(system).mediator 

    // subscribe the test probe to the "info" topic 
    mediator ! Publish("info", probe.ref) 

    "publish a Foo message" in { 
     val msg = Foo("test") 
     interfaceForwardingActor ! msg 
     probe.expectMsg(msg) 
    } 
    } 
} 

我發現的是,probe,這是訂閱的info話題,沒有默認的超時時間內收到消息3秒,斷言失敗。然而有趣的是,我確實看到日誌消息指出接口轉發actor確實在轉發Foo消息。

我在做什麼錯在我的測試?

+0

看到答案後,我投票結束,因爲它是一個簡單的錯字...'發佈'應該是'訂閱'。粗心的錯誤。 :) – erip

回答

1

TestProbe應訂閱了測試代碼的話題:

mediator ! Subscribe("info", probe.ref)

,而不是分佈式的發佈 - 訂閱的

mediator ! Publish("info", probe.ref)

文檔頁面here,以供參考。

+0

哦哇... :(這太傻了。 – erip