• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala TestProbe类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中akka.testkit.TestProbe的典型用法代码示例。如果您正苦于以下问题:Scala TestProbe类的具体用法?Scala TestProbe怎么用?Scala TestProbe使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了TestProbe类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: ApiSpec

//设置package包名称以及导入依赖的类
package au.csiro.data61.magda.registry

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.testkit.TestProbe
import ch.qos.logback.classic.{Level, Logger}
import org.flywaydb.core.Flyway
import org.scalatest.Matchers
import org.scalatest.fixture.FunSpec
import org.slf4j.LoggerFactory

import scala.concurrent.duration._
import scalikejdbc._

abstract class ApiSpec extends FunSpec with ScalatestRouteTest with Matchers with Protocols with SprayJsonSupport {
  case class FixtureParam(api: Api, webHookActorProbe: TestProbe)

  val databaseUrl = Option(System.getenv("npm_package_config_databaseUrl")).getOrElse("jdbc:postgresql://localhost:5432/postgres")

  // Stop Flyway from producing so much spam that Travis terminates the process.
  LoggerFactory.getLogger("org.flywaydb").asInstanceOf[Logger].setLevel(Level.WARN)

  val flyway = new Flyway()
  flyway.setDataSource(databaseUrl, "postgres", "")
  flyway.setSchemas("test")
  flyway.setLocations("classpath:/sql")

  override def testConfigSource =
    s"""
      |db.default.url = "${databaseUrl}?currentSchema=test"
      |authorization.skip = true
      |akka.loglevel = INFO
    """.stripMargin

  override def withFixture(test: OneArgTest) = {
    val webHookActorProbe = TestProbe()
    val api = new Api(webHookActorProbe.ref, testConfig, system, executor, materializer)

    webHookActorProbe.expectMsg(1 millis, WebHookActor.Process)

    DB localTx { implicit session =>
      sql"DROP SCHEMA IF EXISTS test CASCADE".update.apply()
      sql"CREATE SCHEMA test".update.apply()
    }

    flyway.migrate()

    super.withFixture(test.toNoArgTest(FixtureParam(api, webHookActorProbe)))
  }
} 
开发者ID:TerriaJS,项目名称:magda,代码行数:51,代码来源:ApiSpec.scala


示例2: CapacityLimitSpec

//设置package包名称以及导入依赖的类
package akka.io

import akka.testkit.{ TestProbe, AkkaSpec }
import akka.testkit.SocketUtil._
import Tcp._

class CapacityLimitSpec extends AkkaSpec("""
    akka.loglevel = ERROR
    akka.io.tcp.max-channels = 4
    akka.actor.serialize-creators = on
    """)
  with TcpIntegrationSpecSupport {

  "The TCP transport implementation" should {

    "reply with CommandFailed to a Bind or Connect command if max-channels capacity has been reached" in new TestSetup {
      establishNewClientConnection()

      // we now have three channels registered: a listener, a server connection and a client connection
      // so register one more channel
      val commander = TestProbe()
      val addresses = temporaryServerAddresses(2)
      commander.send(IO(Tcp), Bind(bindHandler.ref, addresses(0)))
      commander.expectMsg(Bound(addresses(0)))

      // we are now at the configured max-channel capacity of 4

      val bindToFail = Bind(bindHandler.ref, addresses(1))
      commander.send(IO(Tcp), bindToFail)
      commander.expectMsgType[CommandFailed].cmd should be theSameInstanceAs (bindToFail)

      val connectToFail = Connect(endpoint)
      commander.send(IO(Tcp), connectToFail)
      commander.expectMsgType[CommandFailed].cmd should be theSameInstanceAs (connectToFail)
    }

  }

} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:40,代码来源:CapacityLimitSpec.scala


示例3: TestSetup

//设置package包名称以及导入依赖的类
package akka.io

import scala.annotation.tailrec
import scala.collection.immutable
import akka.testkit.{ AkkaSpec, TestProbe }
import akka.actor.ActorRef
import akka.io.Inet.SocketOption
import akka.testkit.SocketUtil._
import Tcp._

trait TcpIntegrationSpecSupport { _: AkkaSpec ?

  class TestSetup(shouldBindServer: Boolean = true) {
    val bindHandler = TestProbe()
    val endpoint = temporaryServerAddress()

    if (shouldBindServer) bindServer()

    def bindServer(): Unit = {
      val bindCommander = TestProbe()
      bindCommander.send(IO(Tcp), Bind(bindHandler.ref, endpoint, options = bindOptions))
      bindCommander.expectMsg(Bound(endpoint))
    }

    def establishNewClientConnection(): (TestProbe, ActorRef, TestProbe, ActorRef) = {
      val connectCommander = TestProbe()
      connectCommander.send(IO(Tcp), Connect(endpoint, options = connectOptions))
      val Connected(`endpoint`, localAddress) = connectCommander.expectMsgType[Connected]
      val clientHandler = TestProbe()
      connectCommander.sender() ! Register(clientHandler.ref)

      val Connected(`localAddress`, `endpoint`) = bindHandler.expectMsgType[Connected]
      val serverHandler = TestProbe()
      bindHandler.sender() ! Register(serverHandler.ref)

      (clientHandler, connectCommander.sender(), serverHandler, bindHandler.sender())
    }

    @tailrec final def expectReceivedData(handler: TestProbe, remaining: Int): Unit =
      if (remaining > 0) {
        val recv = handler.expectMsgType[Received]
        expectReceivedData(handler, remaining - recv.data.size)
      }

    
    def connectOptions: immutable.Traversable[SocketOption] = Nil
  }

} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:50,代码来源:TcpIntegrationSpecSupport.scala


示例4: LogSourceSpec

//设置package包名称以及导入依赖的类
package akka.remote

import scala.concurrent.duration._
import akka.testkit.AkkaSpec
import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.Props
import akka.event.Logging
import akka.testkit.ImplicitSender
import akka.testkit.TestProbe
import akka.actor.Deploy
import akka.event.Logging.Info
import akka.actor.ExtendedActorSystem

object LogSourceSpec {
  class Reporter extends Actor with ActorLogging {
    def receive = {
      case s: String ?
        log.info(s)
    }
  }
}

@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class LogSourceSpec extends AkkaSpec(
  """
    akka.loglevel = INFO
    akka.actor.provider = "akka.remote.RemoteActorRefProvider"
    akka.remote.netty.tcp.port = 0
  """) {

  import LogSourceSpec._

  val reporter = system.actorOf(Props[Reporter], "reporter")
  val logProbe = TestProbe()
  system.eventStream.subscribe(system.actorOf(Props(new Actor {
    def receive = {
      case i @ Info(_, _, msg: String) if msg contains "hello" ? logProbe.ref ! i
      case _ ?
    }
  }).withDeploy(Deploy.local), "logSniffer"), classOf[Logging.Info])

  "Log events" must {

    "should include host and port for local LogSource" in {
      reporter ! "hello"
      val info = logProbe.expectMsgType[Info]
      info.message should be("hello")
      val defaultAddress = system.asInstanceOf[ExtendedActorSystem].provider.getDefaultAddress
      info.logSource should include(defaultAddress.toString)
    }
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:54,代码来源:LogSourceSpec.scala


示例5: NetworkBrokerLifetimeSpec

//设置package包名称以及导入依赖的类
package net.ruippeixotog.scalafbp.runtime

import scala.language.reflectiveCalls

import akka.actor.{ Actor, Props, Terminated }
import akka.testkit.TestProbe

class NetworkBrokerLifetimeSpec extends NetworkBrokerSpec {

  "A NetworkBroker" should {

    "manage the lifetime of the components" in {

      "instantiate all components in a graph when the network starts" in new BrokerInstance {
        def _graph = graph

        lazy val probe = TestProbe()
        def instanceProps(id: String) = Props(new Actor {
          probe.ref ! s"started_$id"
          def receive = Actor.ignoringBehavior
        })

        lazy val graph = new TwoNodeGraph {
          behavior(n1, instanceProps("n1"))
          behavior(n2, instanceProps("n2"))
        }

        probe must receive.allOf("started_n1", "started_n2")
      }

      "terminate the network when all components terminate" in new BrokerInstance {
        def _graph = graph

        lazy val instanceProps = Props(new Actor {
          context.stop(self)
          def receive = Actor.ignoringBehavior
        })

        lazy val graph = new TwoNodeGraph {
          behavior(n1, instanceProps)
          behavior(n2, instanceProps)
        }

        lifeProbe must receive.like { case Terminated(`broker`) => ok }
      }
    }
  }
} 
开发者ID:ruippeixotog,项目名称:scalafbp,代码行数:49,代码来源:NetworkBrokerLifetimeSpec.scala


示例6: NetworkBrokerSpec

//设置package包名称以及导入依赖的类
package net.ruippeixotog.scalafbp.runtime

import akka.actor.Props
import akka.testkit.TestProbe
import org.specs2.specification.Scope
import spray.json.DefaultJsonProtocol._

import net.ruippeixotog.akka.testkit.specs2.mutable.AkkaSpecification
import net.ruippeixotog.scalafbp.component.PortDataMarshaller
import net.ruippeixotog.scalafbp.component.core.Repeat

abstract class NetworkBrokerSpec extends AkkaSpecification {

  class SingleNodeGraph extends GraphTemplate {
    val n1 = node[String](1, 1)
  }

  class TwoNodeGraph extends GraphTemplate {
    val n1, n2 = node[String](1, 1)
  }

  class ThreeNodeGraph extends GraphTemplate {
    val n1, n2, n3 = node[String](1, 1)
  }

  class ChainGraph[A: PortDataMarshaller] extends GraphTemplate {
    val inNode = node(Repeat)
    val outNode = node[A](1, 1)
    initial("init") ~> (inNode, "in")
    (inNode, "out") ~> (outNode, 1)
  }

  class TwoToTwoGraph extends GraphTemplate {
    val inNode1, inNode2, outNode1, outNode2 = node[String](1, 1)
    (inNode1, 1) ~> (outNode1, 1) <~ (inNode2, 1)
    (inNode1, 1) ~> (outNode2, 1) <~ (inNode2, 1)
  }

  abstract class BrokerInstance(dynamic: Boolean = false) extends Scope {
    def _graph: GraphTemplate
    def externalProbe: TestProbe = null

    val lifeProbe, outputProbe = TestProbe()
    val broker = system.actorOf(Props(
      new NetworkBroker(_graph, dynamic, outputProbe.ref, Option(externalProbe).map(_.ref))))

    lifeProbe.watch(broker)
  }
} 
开发者ID:ruippeixotog,项目名称:scalafbp,代码行数:50,代码来源:NetworkBrokerSpec.scala


示例7: HttpClientAsActorSpec

//设置package包名称以及导入依赖的类
package com.scalaio.http.client

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.testkit.{TestKit, TestProbe}
import com.scalaio.http.client.actor.HttpClientAsActor
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

class HttpClientAsActorSpec() extends TestKit(ActorSystem("MySpec"))
  with WordSpecLike with Matchers with BeforeAndAfterAll {

  import scala.concurrent.ExecutionContext.Implicits.global
  import scala.concurrent.duration._

  override def afterAll {
    // helps avoid abrupt system closure
    Http()
      .shutdownAllConnectionPools()
      .onComplete { _ => system.terminate() }
  }

  "An Http actor" must {

    "consume http endpoints" in {
      val worker = TestProbe("worker")

      // when
      system.actorOf(HttpClientAsActor.props(worker.ref), "httpClientActor")

      // then
      val responseMessage = worker.expectMsgType[String](5.seconds)
      responseMessage shouldBe "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"
    }

  }
} 
开发者ID:fagossa,项目名称:scalaio_akka,代码行数:37,代码来源:HttpClientAsActorSpec.scala


示例8: WireTransferSpec

//设置package包名称以及导入依赖的类
package akka

import BankAccount.{BankAccount, WireTransfer}
import akka.actor.{ActorSystem, Props}
import akka.testkit.{ImplicitSender, TestKit, TestProbe}
import org.scalatest._

class WireTransferSpec(_system: ActorSystem) extends TestKit(_system)
  with FlatSpecLike
  with ImplicitSender
  with Matchers
  with BeforeAndAfterAll {

  def this() = this(ActorSystem("WireTransferSpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  it should "transfer money from A to B in case of sufficient funds on A" in {
    val accountA = TestProbe()
    val accountB = TestProbe()
    val transfer = system.actorOf(Props[WireTransfer])
    transfer ! WireTransfer.Transfer(accountA.ref, accountB.ref, 20)
    accountA.expectMsg(BankAccount.Withdraw(20))
    accountA.reply(BankAccount.Done)
    accountB.expectMsg(BankAccount.Deposit(20))
    accountB.reply(BankAccount.Done)
    expectMsg(WireTransfer.Done)
  }

  it should "not transfer money from A to B in case of insufficient funds on A" in {
    val accountA = TestProbe()
    val accountB = TestProbe()
    val transfer = system.actorOf(Props[WireTransfer])
    transfer ! WireTransfer.Transfer(accountA.ref, accountB.ref, 20)
    accountA.expectMsg(BankAccount.Withdraw(20))
    accountA.reply(BankAccount.Failed)
    expectMsg(WireTransfer.Failed)
  }


} 
开发者ID:zsomboracs,项目名称:akka-bankaccount,代码行数:44,代码来源:WireTransferSpec.scala


示例9: SqsSpec

//设置package包名称以及导入依赖的类
package com.taxis99.amazon.sqs

import akka.testkit.TestProbe
import com.typesafe.config.ConfigFactory
import it.IntegrationSpec
import it.mocks.{TestConsumer, TestProducer, TestType}

import scala.collection.JavaConverters._
import scala.concurrent.duration._

class SqsSpec extends IntegrationSpec {

  val queueName = "integration-test-q"
  val config = ConfigFactory.parseMap(Map[String, String](
      s"sqs.$queueName" -> queueName
    ).asJava)

  implicit val sqs = new SqsClient(config)

  val probe = TestProbe()
  val consumer = new TestConsumer(queueName, probe.ref)
  val producer = new TestProducer(queueName)

  it should "consume the message produce by the producer to the queue" in {
    val msg = TestType("bar", 100)
    
    producer.produce(msg) map { _ =>
      probe expectMsg (10.seconds, msg)
      succeed
    }
  }
} 
开发者ID:99Taxis,项目名称:common-sqs,代码行数:33,代码来源:SqsSpec.scala


示例10: SnsSpec

//设置package包名称以及导入依赖的类
import akka.testkit.TestProbe
import com.taxis99.amazon.sns.SnsClient
import com.taxis99.amazon.sqs.SqsClient
import com.typesafe.config.ConfigFactory
import it.IntegrationSpec
import it.mocks.{TestConsumer, TestPublisher, TestType}

import scala.collection.JavaConverters._
import scala.concurrent.duration._


class SnsSpec extends IntegrationSpec {

  val config = ConfigFactory.parseMap(Map(
    "sns.topic" -> "integration-test-topic",
    "sqs.q1" -> "sns-test-q-1",
    "sqs.q2" -> "sns-test-q-2"
  ).asJava)

  implicit val sqs = new SqsClient(config)
  implicit val sns = new SnsClient(config)

  val probeA = TestProbe()
  val probeB = TestProbe()

  val publisher = new TestPublisher("topic")
  val consumer1 = new TestConsumer("q1", probeA.ref)
  val consumer2 = new TestConsumer("q2", probeB.ref)

  it should "publish a message to an topic and deliver to all queues subscribed" in {
    val msg = TestType("bar", 100)

    publisher.publish(msg) map { _ =>
      probeA expectMsg (10.seconds, msg)
      probeB expectMsg (10.seconds, msg)
      succeed
    }
  }
} 
开发者ID:99Taxis,项目名称:common-sqs,代码行数:40,代码来源:SnsSpec.scala


示例11: ReaperUTest

//设置package包名称以及导入依赖的类
package com.example.util

import akka.actor.{ActorSystem, Props}
import akka.testkit.{ImplicitSender, TestKit, TestProbe}
import com.example.StopSystemAfterAll
import org.scalatest.{FlatSpecLike, ShouldMatchers}

class ReaperUTest
  extends TestKit(ActorSystem("testsystem"))
  with FlatSpecLike
  with ShouldMatchers
  with StopSystemAfterAll
  with ImplicitSender {

  import Reaper._

  override def afterAll(): Unit = {
    system.shutdown()
    super.afterAll()
  }

  trait ReaperFixture {
    val reaper = system.actorOf(Props(new TestReaper(testActor)))
    val actor1 = TestProbe()
    val actor2 = TestProbe()
    val actor3 = TestProbe()
    val actor4 = TestProbe()
  }

  "The Reaper" should "call the allSoulsReaped method after all watched actors are dead" in new ReaperFixture {
    reaper ! WatchMe(actor3.ref)
    reaper ! WatchMe(actor1.ref)

    system.stop(actor1.ref)
    system.stop(actor3.ref)

    expectMsg("Dead")
  }

  it should "fail to call the allSoulsReaped method if not all watched actors are dead" in new ReaperFixture {
    reaper ! WatchMe(actor3.ref)
    reaper ! WatchMe(actor1.ref)

    system.stop(actor1.ref)
    expectNoMsg()
  }

} 
开发者ID:shafiquejamal,项目名称:akka-scala-reaper-seed,代码行数:49,代码来源:ReaperUTest.scala


示例12: UserSocketSpec

//设置package包名称以及导入依赖的类
package actors

import actors.UserSocket.{ChatMessage, Message}
import akka.actor._
import akka.cluster.pubsub.DistributedPubSub
import akka.cluster.pubsub.DistributedPubSubMediator.{SubscribeAck, Subscribe}
import akka.testkit.TestProbe
import org.specs2.mutable._
import play.api.libs.json._

import scala.language.postfixOps

class UserSocketSpec extends Specification {
  val UserId = "user1"

  "A user socket" should {
    val topic = "chat"

    "send chat message to all subscribers" in new AkkaTestkitSpecs2Support {
      implicit val messageWrites = Json.writes[Message]

      val mediator = DistributedPubSub(system).mediator
      val browser = TestProbe()
      val chatMember1 = TestProbe()
      val chatMember2 = TestProbe()
      mediator ! Subscribe(topic, chatMember1.ref)
      mediator ! Subscribe(topic, chatMember2.ref)
      val socket = system.actorOf(UserSocket.props("user1")(browser.ref), "userSocket")
      val message = "hello"

      socket ! Json.toJson(Message(message))

      chatMember1.ignoreMsg({ case SubscribeAck => true })
      chatMember1.expectMsg(ChatMessage(UserId, message))
      chatMember2.ignoreMsg({ case SubscribeAck => true })
      chatMember2.expectMsg(ChatMessage(UserId, message))
    }

    "forward chat message to browser" in new AkkaTestkitSpecs2Support {
      val browser = TestProbe()
      val socket = system.actorOf(UserSocket.props(UserId)(browser.ref), "userSocket")
      val chatMessage = ChatMessage(UserId, "There is important thing to do!")

      socket ! chatMessage

      browser.expectMsg(Json.toJson(chatMessage))
    }
  }
} 
开发者ID:onegrx,项目名称:playakkachat,代码行数:50,代码来源:UserSocketSpec.scala


示例13: ProbeActor

//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.leadership.impl

import akka.actor.{ ActorRef, Props, Actor }
import akka.event.LoggingReceive
import akka.testkit.TestProbe

object ProbeActor {
  def props(testProbe: TestProbe): Props = Props(new ProbeActor(testProbe))

  case class PreStart(self: ActorRef)
  case class PostStop(self: ActorRef)
}

class ProbeActor(testProbe: TestProbe) extends Actor {

  override def preStart(): Unit = {
    testProbe.ref ! ProbeActor.PreStart(self)
  }

  override def postStop(): Unit = {
    testProbe.ref ! ProbeActor.PostStop(self)
  }

  override def receive: Receive = LoggingReceive {
    case any: Any =>
      testProbe.ref.forward(any)
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:29,代码来源:ProbeActor.scala


示例14: CaptureEvents

//设置package包名称以及导入依赖的类
package mesosphere.marathon.test

import akka.actor.ActorDSL._
import akka.actor.{ ActorSystem, PoisonPill, Terminated }
import akka.event.EventStream
import akka.testkit.TestProbe
import mesosphere.marathon.core.event.MarathonEvent

import scala.collection.immutable.Seq
import scala.concurrent.Await
import scala.concurrent.duration.Duration

class CaptureEvents(eventStream: EventStream) {
  
  def forBlock(block: => Unit): Seq[MarathonEvent] = {
    implicit val actorSystem = ActorSystem("captureEvents")

    // yes, this is ugly. Since we only access it in the actor until it terminates, we do have
    // the correct thread sync boundaries in place.

    var capture = Vector.empty[MarathonEvent]
    val captureEventsActor = actor {
      new Act {
        become {
          case captureMe: MarathonEvent => capture :+= captureMe
        }
      }
    }
    eventStream.subscribe(captureEventsActor, classOf[MarathonEvent])
    eventStream.subscribe(captureEventsActor, classOf[String])

    try {
      block
    } finally {
      eventStream.unsubscribe(captureEventsActor)
      captureEventsActor ! PoisonPill
      val probe = TestProbe()
      probe.watch(captureEventsActor)
      probe.expectMsgClass(classOf[Terminated])
      Await.result(actorSystem.terminate(), Duration.Inf)
    }

    capture
  }

} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:47,代码来源:CaptureEvents.scala


示例15: StopActorTest

//设置package包名称以及导入依赖的类
package mesosphere.marathon.upgrade

import akka.actor.{ ActorRef, Props }
import akka.testkit.TestActor.{ AutoPilot, NoAutoPilot }
import akka.testkit.TestProbe
import mesosphere.marathon.test.MarathonActorSupport
import mesosphere.marathon.upgrade.DeploymentActor.Cancel
import org.scalatest.{ FunSuiteLike, Matchers }

import scala.concurrent.duration._
import scala.concurrent.{ Await, Promise }

class StopActorTest extends MarathonActorSupport with FunSuiteLike with Matchers {

  test("Stop") {
    val promise = Promise[Boolean]()
    val probe = TestProbe()

    probe.setAutoPilot(new AutoPilot {
      def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
        case Cancel(reason) =>
          system.stop(probe.ref)
          NoAutoPilot
      }
    })
    val ref = system.actorOf(Props(classOf[StopActor], probe.ref, promise, new Exception))

    watch(ref)
    expectTerminated(ref)

    Await.result(promise.future, 5.seconds) should be(true)
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:34,代码来源:StopActorTest.scala


示例16: UnhandledMessageWatcherSpec

//设置package包名称以及导入依赖的类
package com.tpalanga.newsletter.utils

import akka.actor.{Actor, ActorSystem, Props}
import akka.event.Logging.LogEvent
import akka.testkit.{ImplicitSender, TestKit, TestProbe}
import com.tpalanga.newsletter.util.UnhandledMessageWatcher
import org.scalatest.{FlatSpecLike, Matchers}

object UnhandledMessageWatcherSpec {

  abstract class Test(implicit system: ActorSystem) {
    val watcher = system.actorOf(UnhandledMessageWatcher.props())
    val logProbe = TestProbe()
    system.eventStream.subscribe(logProbe.ref, classOf[LogEvent])

    val destination = system.actorOf(Props(new Actor {
      override def receive: Receive = {
        case 'Handled =>
      }
    }))

  }
}

class UnhandledMessageWatcherSpec extends TestKit(ActorSystem("UnhandledMessageWatcherSpec")) with FlatSpecLike with Matchers with ImplicitSender {
  import UnhandledMessageWatcherSpec._

  "UnhandledMessageWatcher" should "log unhandled messages" in new Test {
    destination ! 'Unhandled

    val event = logProbe.fishForMessage() {
      case akka.event.Logging.Error(_, _, _, msg) if msg.toString startsWith "UnhandledMessage:" =>
        true
      case _ =>
        false
    }
  }

  it should "log DeadLetters" in new Test {
    system.stop(destination)
    Thread.sleep(100)
    destination ! 'Handled

    val event = logProbe.fishForMessage() {
      case akka.event.Logging.Warning(_, _, msg) if msg.toString startsWith "DeadLetter:" =>
        true
      case _ =>
        false
    }
  }
} 
开发者ID:tpalanga,项目名称:akka-http-microservice,代码行数:52,代码来源:UnhandledMessageWatcherSpec.scala


示例17: ProtocolHandlerActorTest

//设置package包名称以及导入依赖的类
package fafa.actor

import akka.actor.Props
import akka.testkit.TestProbe
import fafa.messages.{IsReadyMessage, ReadyOkMessage}

import scala.concurrent.duration._


class ProtocolHandlerActorTest extends BaseActorTest {

  val engineProbe = TestProbe()
  val ioActor = testActor
  val protocolHandlerRef = system.actorOf(Props(classOf[ProtocolHandlerActor], engineProbe.ref))

  override def beforeAll = {
    protocolHandlerRef ! ioActor // set IO actor
  }

  "ProtocolHandlerActor" should "forward serialized messages to io actor" in {
    within(500 millis) {
      protocolHandlerRef ! ReadyOkMessage()
      expectMsg("readyok")
    }
  }

  it should "forward deserialized messages to the engine" in {
    within(500 millis) {
      protocolHandlerRef ! "isready"
      engineProbe.expectMsg(IsReadyMessage())
    }
  }
} 
开发者ID:Macok,项目名称:fafachess,代码行数:34,代码来源:ProtocolHandlerActorTest.scala


示例18: StringCounterSpec

//设置package包名称以及导入依赖的类
package com.taintech.common.actor

import akka.actor.{ActorSystem, Props}
import akka.testkit.{ImplicitSender, TestKit, TestProbe}
import StringCounter.{GetTopStrings, StringCount}
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, MustMatchers}


class StringCounterSpec extends TestKit(ActorSystem("test-system"))
  with FlatSpecLike
  with ImplicitSender
  with BeforeAndAfterAll
  with MustMatchers {
  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "Counter Actor" should "handle GetTopString message with using TestProbe" in {
    val sender = TestProbe()

    val counter = system.actorOf(Props[StringCounter])

    sender.send(counter, "a")
    sender.send(counter, "c")
    sender.send(counter, "c")
    sender.send(counter, "b")
    sender.send(counter, "b")
    sender.send(counter, "c")

    sender.send(counter, GetTopStrings(2))
    val state = sender.expectMsgType[List[StringCount]]
    state must equal(List(StringCount("c", 3), StringCount("b", 2)))
  }
} 
开发者ID:taintech,项目名称:AmazonFineFoods,代码行数:35,代码来源:StringCounterSpec.scala


示例19: TaskProxyBuilder

//设置package包名称以及导入依赖的类
package actors.workflow.tasks

import actors.workflow.AWSSupervisorStrategy
import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import akka.testkit.TestProbe
import utils.{ActorFactory, PropFactory}

object TaskProxyBuilder {
  def apply[T <: PropFactory](probe: TestProbe, ref: T, actorSystem: ActorSystem,
                              actorFactory: ActorFactory): ActorRef = {
    actorSystem.actorOf(Props(new Actor {
      val parent = context.actorOf(Props(new Actor with AWSSupervisorStrategy {
        val child = actorFactory(ref, context, null, null)

        def receive = {
          case x if sender() == child => context.parent ! x
          case x => child forward x
        }
      }))

      def receive = {
        case x if sender() == parent => probe.ref forward x
        case x => parent forward x
      }
    }))
  }
} 
开发者ID:lifeway,项目名称:Chadash,代码行数:28,代码来源:TaskProxyBuilder.scala


示例20: UserServiceSpec

//设置package包名称以及导入依赖的类
package org.cristal.service

import akka.actor.ActorSystem
import akka.testkit.{ImplicitSender, TestKit, TestProbe}
import org.cristal.model.NewUser
import org.cristal.repository.UserRepository
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
import scala.concurrent.duration._

class UserServiceSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {

    def this() = this(ActorSystem("UserServiceSpecSystem"))

    override def afterAll {
      TestKit.shutdownActorSystem(system)
    }

  "A UserService Actor" should {
    "send a create message to a repository user actor" in {
      val userRepository = TestProbe()
      val userService = system.actorOf(UserService.props(userRepository.ref))
      val newUser = NewUser("name", "my_password", "[email protected]", "John", "Doe")
      userService ! UserService.CreateUser(newUser)
      userRepository.expectMsg(500 millis, UserRepository.CreateUser(newUser, self))
    }

    "send a retrieve message to a repository user actor" in {
      val userRepository = TestProbe()
      val userService = system.actorOf(UserService.props(userRepository.ref))
      userService ! UserService.RetrieveUser()
      userRepository.expectMsg(500 millis, UserRepository.RetrieveUser())
    }
  }

} 
开发者ID:frecano,项目名称:cristal,代码行数:37,代码来源:UserServiceSpec.scala



注:本文中的akka.testkit.TestProbe类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala DefaultJsonProtocol类代码示例发布时间:2022-05-23
下一篇:
Scala Arbitrary类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap