我有一个演员,他的唯一职责是转发从外部接口(命令行、用户等)接收的消息。合适的话题。我想测试它是否正确地发布了这些消息。
我需要创建一些虚拟订阅者,他们将期望消息发布到某个主题,并对接收到的消息进行断言。
下面是我试图意识到的代码:
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秒的默认超时时间内接收消息,断言失败。然而,有趣的是,我确实看到了日志消息,说明接口转发参与者确实在转发Foo消息。
我在考试中做错了什么?
发布于 2016-12-28 13:46:08
TestProbe应该订阅测试代码中的主题:
mediator ! Subscribe("info", probe.ref)
而不是
mediator ! Publish("info", probe.ref)
分布式发布-订阅的文档页是这里,以供参考。
https://stackoverflow.com/questions/41347633
复制相似问题