首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Akka集群中测试发行者到DistributedPubSub?

如何在Akka集群中测试发行者到DistributedPubSub?
EN

Stack Overflow用户
提问于 2016-12-27 15:12:51
回答 1查看 566关注 0票数 0

我有一个演员,他的唯一职责是转发从外部接口(命令行、用户等)接收的消息。合适的话题。我想测试它是否正确地发布了这些消息。

我需要创建一些虚拟订阅者,他们将期望消息发布到某个主题,并对接收到的消息进行断言。

下面是我试图意识到的代码:

Messages.scala

代码语言:javascript
复制
case class Foo(foo: String)

InterfaceForwardingActor.scala

代码语言:javascript
复制
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

代码语言:javascript
复制
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秒的默认超时时间内接收消息,断言失败。然而,有趣的是,我确实看到了日志消息,说明接口转发参与者确实在转发Foo消息。

我在考试中做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-28 13:46:08

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

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

而不是

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

分布式发布-订阅的文档页是这里,以供参考。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41347633

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档