如何在Akka Cluster中测试发布者到DistributedPubSub?

时间:2016-12-27 15:12:52

标签: scala unit-testing akka-cluster 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消息。

我的测试中我做错了什么?

1 个答案:

答案 0 :(得分:1)

TestProbe应该订阅测试代码中的主题:

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

而不是

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

分布式pub-sub的文档页面为here,供参考。