本文整理汇总了Scala中akka.testkit.TestActorRef类的典型用法代码示例。如果您正苦于以下问题:Scala TestActorRef类的具体用法?Scala TestActorRef怎么用?Scala TestActorRef使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TestActorRef类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: HelloAkkaSpec
//设置package包名称以及导入依赖的类
import org.scalatest.{ BeforeAndAfterAll, FlatSpecLike, Matchers }
import akka.actor.{ Actor, Props, ActorSystem }
import akka.testkit.{ ImplicitSender, TestKit, TestActorRef }
import scala.concurrent.duration._
class HelloAkkaSpec(_system: ActorSystem)
extends TestKit(_system)
with ImplicitSender
with Matchers
with FlatSpecLike
with BeforeAndAfterAll {
def this() = this(ActorSystem("HelloAkkaSpec"))
override def afterAll: Unit = {
system.shutdown()
system.awaitTermination(10.seconds)
}
"An HelloAkkaActor" should "be able to set a new greeting" in {
val greeter = TestActorRef(Props[Greeter])
greeter ! WhoToGreet("testkit")
greeter.underlyingActor.asInstanceOf[Greeter].greeting should be("hello, testkit")
}
it should "be able to get a new greeting" in {
val greeter = system.actorOf(Props[Greeter], "greeter")
greeter ! WhoToGreet("testkit")
greeter ! Greet
expectMsgType[Greeting].message.toString should be("hello, testkit")
}
}
开发者ID:rzrelyea,项目名称:scala-akka-web-crawler,代码行数:33,代码来源:HelloAkkaSpec.scala
示例2: AkkademyDbSpec
//设置package包名称以及导入依赖的类
import akka.actor.{ActorSystem, Props}
import akka.testkit.TestActorRef
import akka.util.Timeout
import com.example.{AkkademyDb, ScalaPongActor, SetRequest}
import org.scalatest.{FunSpecLike, _}
import scala.concurrent.duration._
class AkkademyDbSpec extends FunSpecLike with Matchers {
implicit val system = ActorSystem()
implicit val timeout = Timeout(5 seconds)
describe("akkademyDb") {
describe("given SetRequest") {
it("should place key/value into your map") {
val actorRef = TestActorRef(new AkkademyDb)
actorRef ! SetRequest("key", "value")
val akkademyDb = actorRef.underlyingActor
akkademyDb.map.get("key") should equal(Some("value"))
}
}
}
}
class ScalaPongActorSpec extends FunSpecLike with Matchers {
implicit val system = ActorSystem()
implicit val timeout = Timeout(5 seconds)
describe("scalaPongActor") {
describe("given Ping") {
it("should return message Pong") {
val actorRef = system.actorOf(Props[ScalaPongActor], "PongFoo")
actorRef ! "ping"
true
}
}
}
}
开发者ID:hanchenyi,项目名称:FirstAkkaProject,代码行数:43,代码来源:AkkademyDbSpec.scala
示例3: NotificacaoSpec
//设置package包名称以及导入依赖的类
package com.exemplo5
import akka.actor.ActorSystem
import akka.testkit.{ImplicitSender, TestActorRef, TestKit}
import com.common.{Notificacao, TipoNotificacao}
import com.exemplo5.ColetorNotificacoesActor.{ContarNotificacoes, EnviarNotificacao}
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
class NotificacaoSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
with WordSpecLike with Matchers with BeforeAndAfterAll {
def this() = this(ActorSystem("NotificacaoActorSystem"))
override def afterAll {
TestKit.shutdownActorSystem(system)
}
"Como coletor notificacoes " must {
"receber uma mensagem e armazenar na lista de notificacoes" in {
val coletorAtor = TestActorRef[ColetorNotificacoesActor]
coletorAtor ! EnviarNotificacao(Notificacao(1, "[email protected]", "Pagamento realizado no valor de R$ 100,00", TipoNotificacao.PAGAMENTO))
coletorAtor ! EnviarNotificacao(Notificacao(2, "[email protected]", "Saque realizado no valor de R$ 50,00", TipoNotificacao.SAQUE))
coletorAtor ! ContarNotificacoes
coletorAtor.underlyingActor.notificacoes.size shouldEqual 2
}
}
"Como coletor notificacoes " must {
"contar a quantidade de notificacoes e responder" in {
val coletorAtor = TestActorRef[ColetorNotificacoesActor]
coletorAtor ! ContarNotificacoes
expectMsg(2)
}
}
}
开发者ID:otavioucdb,项目名称:akka_sample,代码行数:39,代码来源:NotificacaoSpec.scala
示例4: TweetStreamerActorSpec
//设置package包名称以及导入依赖的类
package core
import akka.actor.ActorSystem
import org.specs2.mutable.SpecificationLike
import akka.testkit.{TestActorRef, TestKit, ImplicitSender}
import domain.Tweet
import spray.http.Uri
class TweetStreamerActorSpec extends TestKit(ActorSystem()) with SpecificationLike with ImplicitSender {
sequential
val port = 12345
val tweetStream = TestActorRef(new TweetStreamerActor(Uri(s"http://localhost:$port/"), testActor) with TwitterAuthorization {
def authorize = identity
})
"Streaming tweets" >> {
"Should unmarshal one tweet" in {
val twitterApi = TwitterApi(port)
tweetStream ! "typesafe"
val tweet = expectMsgType[Tweet]
tweet.text mustEqual "Aggressive Ponytail #freebandnames"
tweet.user.lang mustEqual "en"
tweet.user.id mustEqual "137238150"
tweet.place mustEqual None
twitterApi.stop()
success
}
}
}
开发者ID:frankfarrell,项目名称:irelandweather,代码行数:34,代码来源:TweetStreamerActorSpec.scala
示例5: RestRoutingSpecs
//设置package包名称以及导入依赖的类
package com.cart.routing
import java.util.UUID
import org.scalatest.FlatSpec
import org.scalatest.Matchers
import com.cart.Cart
import com.cart.Carts
import com.cart.GetCarts
import com.cart.RestMessage
import akka.testkit.TestActorRef
import akka.testkit.TestProbe
import spray.routing.Route
import spray.testkit.ScalatestRouteTest
class RestRoutingSpecs extends FlatSpec with ScalatestRouteTest with Matchers {
val getCartsService = TestProbe()
def restRouting = TestActorRef(new RestRouting() {
override def carts(message: RestMessage): Route =
ctx => perRequest(ctx, getCartsService.ref, message)
})
"RestRouting" should "get Carts" in {
val getCarts = Get("/carts") ~> restRouting.underlyingActor.route
getCartsService.expectMsg(GetCarts())
val uuid = UUID.randomUUID().toString()
getCartsService.reply(Carts(Seq(Cart(uuid))))
getCarts ~> check {
responseAs[String] should equal(s"""{"carts":[{"id":"$uuid"}]}""")
}
}
}
开发者ID:bbiletskyy,项目名称:shopping-cart-service,代码行数:39,代码来源:RestRoutingSpecs.scala
示例6: AkkademyDbSpec
//设置package包名称以及导入依赖的类
package akkademy.server
import akka.actor.ActorSystem
import akka.testkit.TestActorRef
import akka.util.Timeout
import org.scalatest.{FunSpecLike, Matchers}
import scala.concurrent.duration._
class AkkademyDbSpec extends FunSpecLike with Matchers {
implicit val system = ActorSystem()
implicit val timeout = Timeout(5 seconds)
describe("akkademyDb") {
describe("given SetRequest") {
it("should place key/value into map") {
val actorRef: TestActorRef[AkkademyDb] = TestActorRef(new AkkademyDb)
actorRef ! SetRequest("key", "value")
val akkademyDb = actorRef.underlyingActor
akkademyDb.map.get("key") should equal(Some("value"))
}
}
describe("given two SetRequest") {
it("should place two key/value into map") {
val actorRef: TestActorRef[AkkademyDb] = TestActorRef(new AkkademyDb)
actorRef ! SetRequest("key", "value")
actorRef ! SetRequest("name", "vito")
val akkademyDb = actorRef.underlyingActor
akkademyDb.map.get("key") should equal(Some("value"))
akkademyDb.map.get("name") should equal(Some("vito"))
}
}
}
}
开发者ID:is-land,项目名称:examples-akka,代码行数:38,代码来源:AkkademyDbSpec.scala
示例7: ReadActorSpec
//设置package包名称以及导入依赖的类
package com.example
import akka.actor.ActorSystem
import akka.testkit.{ImplicitSender, TestActorRef, TestKit, TestProbe}
import com.example.ReaderActor._
import com.example.ServerActor.ReaderRequest
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
class ReadActorSpec extends TestKit(ActorSystem("ReaderActorSpec")) with ImplicitSender
with WordSpecLike with Matchers with BeforeAndAfterAll {
override def afterAll {
TestKit.shutdownActorSystem(system)
}
val serverActor = TestProbe()
"A Read Actor " must {
val testReadActor = TestActorRef[ReaderActor](ReaderActor.props(system.actorSelection(serverActor.ref.path), 10))
var messages = Seq[ReaderRequest]()
"send 10 new UUIDs to the server" in {
messages = serverActor receiveN 10 map (_.asInstanceOf[ReaderRequest])
messages foreach { msg =>
msg.i shouldEqual 0
}
}
"Correctly update the state of a UUID sequence" in {
val subsetId = messages take 1 map (_.uuid)
for {
id <- subsetId
update <- 1 to 10
} testReadActor ! SequenceUpdate(id, update)
val actorState = testReadActor.underlyingActor.idMap
subsetId foreach { id =>
actorState.get(id) shouldEqual Some(10)
}
}
"Correctly remove the state of its UUID sequences and start new ones" in {
val subsetIds = messages take 5 map (_.uuid)
for (id <- subsetIds) testReadActor ! SequenceUpdate(id, -1)
val actorState = testReadActor.underlyingActor.idMap
actorState.size shouldEqual 10
subsetIds foreach { id =>
actorState.get(id) shouldEqual None
}
}
}
}
开发者ID:enear,项目名称:server-writer-reader,代码行数:57,代码来源:ReadActorSpec.scala
示例8: TransferCoordinatorTest
//设置package包名称以及导入依赖的类
package com.datio.reactransaction.actor
import akka.actor.{ActorRef, ActorSystem}
import akka.testkit.{TestProbe, TestActorRef, TestKit}
import com.datio.reactransaction.model.{Transaction, Transfer}
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.{MustMatchers, WordSpecLike}
@RunWith(classOf[JUnitRunner])
class TransferCoordinatorTest extends TestKit(ActorSystem("testAkkaSystem"))
with WordSpecLike with MustMatchers {
val probeSrc: TestProbe = TestProbe()
val probeDst = TestProbe()
val transferActor = TestActorRef(new TransferCoordinator {
override def getOrCreateAccountActor(id: Long): ActorRef = {
if (id == 1) probeSrc.ref else probeDst.ref
}
})
"Transfer Coordinator actor" must {
"make a transfer" in {
val ten = 10
val amount = BigDecimal(ten)
transferActor ! Transaction(1, 2, amount)
probeSrc.expectMsg(Transfer(-amount))
probeDst.expectMsg(Transfer(amount))
}
}
}
开发者ID:joseluisillanadatio,项目名称:ingestion-api-akka,代码行数:38,代码来源:TransferCoordinatorTest.scala
示例9: TestEventSource
//设置package包名称以及导入依赖的类
package avionics
import akka.actor.{ActorRef, ActorSystem, Actor}
import akka.actor.Actor.Receive
import akka.testkit.{TestActorRef, TestKit}
import org.scalatest.{Matchers, BeforeAndAfterAll, WordSpecLike}
class TestEventSource
extends Actor
with ProductionEventSource {
override def receive: Receive = eventSourceReceive
}
class EventSourceSpec
extends TestKit(ActorSystem("EventSourceSpec"))
with WordSpecLike
with Matchers
with BeforeAndAfterAll {
import EventSource._
override def afterAll() { system.shutdown() }
"EventSource" should {
"allow us to register a listener" in {
val real = TestActorRef[TestEventSource].underlyingActor
real.receive(RegisterListener(testActor))
real.listeners should contain (testActor)
}
"allow us to unregister a listener" in {
val real = TestActorRef[TestEventSource].underlyingActor
real.receive(RegisterListener(testActor))
real.receive(UnregisterListener(testActor))
real.listeners.size should be (0)
}
"send the event to our test actor" in {
val testA = TestActorRef[TestEventSource]
testA ! RegisterListener(testActor)
testA.underlyingActor.sendEvent("Fibonacci")
expectMsg("Fibonacci")
}
}
}
开发者ID:mingik,项目名称:akka-concurrency,代码行数:42,代码来源:EventSourceSpec.scala
示例10: TestFlightAttendant
//设置package包名称以及导入依赖的类
package avionics
import akka.actor.{Props, ActorSystem}
import akka.testkit.{TestActorRef, ImplicitSender, TestKit}
import com.typesafe.config.ConfigFactory
import org.scalatest.{Matchers, WordSpecLike}
object TestFlightAttendant {
def apply() = new FlightAttendant with AttendantResponsiveness {
val maxResponseTimeMS = 1
}
}
class TestFlightAttendantSpec
extends TestKit(ActorSystem("FlightAttendantSpec", ConfigFactory.parseString("akka.scheduler.tick-duration = 1ms")))
with ImplicitSender
with WordSpecLike
with Matchers {
import FlightAttendant._
"FlightAttendant" should {
"get a drink when asked" in {
val a = TestActorRef(Props(TestFlightAttendant()))
a ! GetDrink("Soda")
expectMsg(Drink("Soda"))
}
}
}
开发者ID:mingik,项目名称:akka-concurrency,代码行数:29,代码来源:TestFlightAttendantSpec.scala
示例11: CounterSpec
//设置package包名称以及导入依赖的类
package myActorTest
import akka.testkit.TestKit
import akka.actor.ActorSystem
import org.scalatest.WordSpecLike
import org.scalatest.BeforeAndAfterAll
import akka.testkit.TestActorRef
class CounterSpec extends TestKit(ActorSystem("CounterSpec"))
with WordSpecLike with BeforeAndAfterAll {
override def afterAll(): Unit = {
system.terminate
}
"A Counter" must {
"increment the value" in {
import Counter._
val counter = TestActorRef[Counter]
counter ! Incr
assert (counter.underlyingActor.count == 1)
}
}
}
开发者ID:Passarinho4,项目名称:reactive-lab3,代码行数:28,代码来源:CounterSpec.scala
示例12: UserActorSpec
//设置package包名称以及导入依赖的类
package actors
import akka.actor._
import akka.testkit.{TestActorRef, _}
import com.typesafe.config.ConfigFactory
import org.scalatest.MustMatchers
import play.api.libs.json._
import scala.concurrent.duration._
class UserActorSpec extends TestKitSpec with MustMatchers {
"UserActor" should {
val symbol = "ABC"
val price = 123
val history = scala.collection.immutable.Seq[Double](0.1, 1.0)
val configuration = play.api.Configuration.apply(ConfigFactory.parseString(
"""
|default.stocks = ["GOOG", "AAPL", "ORCL"]
""".stripMargin))
"send a stock when receiving a StockUpdate message" in {
val out = TestProbe()
val stocksActor = TestProbe()
val userActorRef = TestActorRef[UserActor](Props(new UserActor(out.ref, stocksActor.ref, configuration)))
val userActor = userActorRef.underlyingActor
// send off the stock update...
userActor.receive(StockUpdate(symbol, price))
// ...and expect it to be a JSON node.
val jsObj: JsObject = out.receiveOne(500 millis).asInstanceOf[JsObject]
jsObj \ "type" mustBe JsDefined(JsString("stockupdate"))
jsObj \ "symbol" mustBe JsDefined(JsString(symbol))
jsObj \ "price" mustBe JsDefined(JsNumber(price))
}
"send the stock history when receiving a StockHistory message" in {
val out = TestProbe()
val stocksActor = TestProbe()
val userActorRef = TestActorRef[UserActor](Props(new UserActor(out.ref, stocksActor.ref, configuration)))
val userActor = userActorRef.underlyingActor
// send off the stock update...
userActor.receive(StockHistory(symbol, history))
val jsObj: JsObject = out.receiveOne(500 millis).asInstanceOf[JsObject]
// ...and expect it to be a JSON node.
jsObj \ "type" mustBe JsDefined(JsString("stockhistory"))
jsObj \ "symbol" mustBe JsDefined(JsString("ABC"))
jsObj \ "history" mustBe JsDefined(Json.arr(JsNumber(0.1), JsNumber(1.0)))
}
}
}
开发者ID:ChrisCooper,项目名称:customer-feedback-screen,代码行数:59,代码来源:UserActorSpec.scala
示例13: AkkadmeyDBSecondTest
//设置package包名称以及导入依赖的类
package com.harmeetsingh13.chapter1
import akka.actor.ActorSystem
import akka.testkit.TestActorRef
import com.harmeetsingh13.chapter1.examples.AkkadmeyDBSecond
import com.harmeetsingh13.chapter1.messages.Message
import org.scalatest.{BeforeAndAfterEach, Matchers, FunSpecLike}
class AkkadmeyDBSecondTest extends FunSpecLike with Matchers with BeforeAndAfterEach {
implicit val system = ActorSystem();
describe("akkadmey-db-homework-first-test"){
describe("receive-msg-correctly"){
it("should receive message correctly"){
val actorRef = TestActorRef(new AkkadmeyDBSecond)
actorRef ! Message("First Message .... ")
actorRef ! Message("Second Message .... ")
val akkadmeyDb = actorRef.underlyingActor;
akkadmeyDb.messages.apply(0) should equal("First Message ....")
akkadmeyDb.messages.apply(1) should equal("Second Message ....")
}
}
}
}
开发者ID:harmeetsingh0013,项目名称:Akka-practice-using-scala,代码行数:27,代码来源:AkkadmeyDBSecondTest.scala
示例14: AkkadmeyDBFirstTest
//设置package包名称以及导入依赖的类
package com.harmeetsingh13.chapter1
import akka.actor.ActorSystem
import akka.testkit.TestActorRef
import com.harmeetsingh13.chapter1.examples.AkkadmeyDBFirst
import com.harmeetsingh13.chapter1.messages.SetRequest
import org.scalatest.{Matchers, FunSpecLike, BeforeAndAfterEach, FunSpec}
import org.scalatest.matchers.Matcher
class AkkadmeyDBFirstTest extends FunSpecLike with Matchers with BeforeAndAfterEach{
implicit val system = ActorSystem()
describe("akkadmey-db-first-test"){
describe("given SetRequest"){
it("should place key/value into map"){
val actorRef = TestActorRef(new AkkadmeyDBFirst)
actorRef ! SetRequest("key", "value")
val akkadmeyDb = actorRef.underlyingActor
akkadmeyDb.map.get("key") should equal (Some("value"))
}
}
}
}
开发者ID:harmeetsingh0013,项目名称:Akka-practice-using-scala,代码行数:25,代码来源:AkkadmeyDBFirstTest.scala
示例15: AcademyDbSpec
//设置package包名称以及导入依赖的类
package com.sunnymix.academydb
import akka.actor.ActorSystem
import akka.testkit.TestActorRef
import org.scalatest.{BeforeAndAfterEach, FunSpecLike, Matchers}
import com.sunnymix.academydb.messages._
class AcademyDbSpec extends FunSpecLike with Matchers with BeforeAndAfterEach {
implicit val system = ActorSystem()
describe("AcademyDB") {
describe("given SetRequest") {
it("should place key/value to map") {
val actorRef = TestActorRef(new AcademyDB)
val akkademyDb = actorRef.underlyingActor
actorRef ! SetRequest("key", "value")
akkademyDb.map.get("key") should equal(Some("value"))
actorRef ! SetRequest("key", "new value")
akkademyDb.map.get("key") should equal(Some("new value"))
}
}
}
}
开发者ID:sunnymix,项目名称:academydb,代码行数:28,代码来源:AcademyDbSpec.scala
示例16: WateringListenerTest
//设置package包名称以及导入依赖的类
package mqtt.watering
import java.time.{Clock, Instant}
import akka.actor.{ActorSystem, Props}
import akka.testkit.TestActorRef
import com.softwaremill.macwire.wire
import model.sensor._
import model.sensor.impl.{LocationRepositorySql, LocationSql, SensorRepositorySql}
import mqtt.MqttListenerMessage.ConsumeMessage
import org.scalamock.scalatest.MockFactory
import org.scalatest.{Matchers, WordSpec}
class WateringListenerTest extends WordSpec with Matchers with MockFactory {
"WateringListener" when {
implicit val system = ActorSystem()
val clock = mock[Clock]
val instant = Instant.ofEpochSecond(22)
(clock.instant _).expects().returning(instant).atLeastOnce()
"receives the message" should {
"store it in dao if the message is correct" in {
val locationRepository = mock[LocationRepositorySql]
val sensorRepository = mock[SensorRepositorySqlWithCtor]
val listener = TestActorRef[WateringListener](Props(wire[WateringListener]))
val sensor = mock[Sensor]
val humidityPhenomenon = mock[MeasuredPhenomenon]
val wateringPhenomenon = mock[MeasuredPhenomenon]
val location = LocationSql("watering-ibiscus", "label")
(locationRepository.findOrCreateLocation _).expects("watering-ibiscus").returning(location)
(sensorRepository.findOrCreateSensor _).expects(location, "watering").returning(sensor)
(sensor.findOrCreatePhenomenon _).expects( "humidity", "", IdentityMeasurementAggregationStrategy).returning(humidityPhenomenon)
(sensor.addMeasurement _).expects(Measurement(86, Instant.ofEpochSecond(22)), humidityPhenomenon)
(sensor.findOrCreatePhenomenon _).expects( "watering", "", BooleanMeasurementAggregationStrategy).returning(wateringPhenomenon)
(sensor.addMeasurement _).expects(Measurement(10, Instant.ofEpochSecond(22)), wateringPhenomenon)
val correctJson = """ {"ts":8119,"tm":{"hu":{"a":86,"bl":512,"md":1000,"bs":10,"pd":30},"wa":{"ip":true,"wp":20000,"wt":5000},"wlh":true}}"""
listener ! ConsumeMessage("home/watering/ibisek/telemetry", correctJson)
}
}
}
class SensorRepositorySqlWithCtor extends SensorRepositorySql(null, null)
}
开发者ID:vavravl1,项目名称:home_center,代码行数:50,代码来源:WateringListenerTest.scala
示例17: SessionActorSpec
//设置package包名称以及导入依赖的类
package com.example
import akka.actor.{ActorSystem, Props}
import akka.testkit.{ImplicitSender, TestActorRef, TestKit, TestProbe}
import com.example.events.{EventProducer, Request}
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
import scala.concurrent.duration._
class SessionActorSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
with WordSpecLike with Matchers with BeforeAndAfterAll {
def this() = this(ActorSystem("MySpec"))
override def afterAll {
TestKit.shutdownActorSystem(system)
}
"A Session actor" must {
"receive an event and add it to history" in {
val request: Request = new EventProducer(1).tick.head
val timeoutDuration = 10.seconds
val sessionActor = TestActorRef(new SessionActor(request.session, timeoutDuration, TestProbe().ref))
sessionActor ! SessionActor.AddRequest(request)
sessionActor.underlyingActor.requestHistory.size shouldBe 1
}
}
"A Session actor" must {
"receive an InactivityTimeout message in case it hasn't received a request in 5 min" in {
val request: Request = new EventProducer(1).tick.head
val timeoutDuration = 100.millis
val sessionActor = TestActorRef(new SessionActor(request.session, timeoutDuration, TestProbe().ref))
val probe = TestProbe()
probe.watch(sessionActor)
within(200.millis) {
probe.expectTerminated(sessionActor)
}
}
}
"A Session actor" must {
"send requestHistory to StatsActor" in {
val request: Request = new EventProducer(1).tick.head
val timeoutDuration = 100.millis
val statsActorMock = TestProbe()
system.actorOf(Props(new SessionActor(request.session, timeoutDuration, statsActorMock.ref)))
statsActorMock.expectMsgPF(200.millis) {
case _: StatsActor.AggregateStats => false
case _ => throw new IllegalStateException()
}
}
}
}
开发者ID:dgolovan,项目名称:AkkaIntro,代码行数:61,代码来源:SessionActorSpec.scala
示例18: CanyonMonkeyIT
//设置package包名称以及导入依赖的类
package com.fhuertas.monkey.models
import akka.actor.{ActorSystem, Terminated}
import akka.testkit.{ImplicitSender, TestActorRef, TestKit}
import com.fhuertas.monkey.orchestration.OrchestrationConfig
import com.fhuertas.monkey.utils.{FastConfiguration, FastMonkey}
import org.scalatest.{Matchers, WordSpecLike}
class CanyonMonkeyIT extends TestKit(ActorSystem("MySpec"))
with ImplicitSender
with WordSpecLike
with Matchers
with FastConfiguration {
def getMaxTime: Int = getInt(MonkeyConfig.KEY_CROSS_TIME).get +
getInt(MonkeyConfig.KEY_ROPE_TIME).get +
getInt(OrchestrationConfig.KEY_MAX_TIME).get
def getNumMonkeys: Int = getInt(OrchestrationConfig.KEY_NUM_MONKEYS).get
"Canyon and Monkey" should {
"orchestrate" in new FastConfiguration {
val canyon = TestActorRef(Canyon.props)
val monkeys = 1 to getNumMonkeys map (_ => watch(TestActorRef(FastMonkey.props(canyon))))
val maxTime = getNumMonkeys * getMaxTime
monkeys.foreach(_ => expectMsgClass(classOf[Terminated]))
}
}
}
开发者ID:fhuertas,项目名称:monkey,代码行数:31,代码来源:CanyonMonkeyIT.scala
示例19: EchoEndpoint
//设置package包名称以及导入依赖的类
package streaming
import java.time.Instant
import javax.websocket.server.ServerEndpoint
import javax.websocket.{OnMessage, Session}
import akka.actor.ActorSystem
import akka.testkit.{TestActorRef, TestKitBase, TestProbe}
import co.coinsmith.kafka.cryptocoin.streaming.{Connect, WebsocketActor}
import org.glassfish.tyrus.test.tools.TestContainer
import org.json4s.JsonAST.JObject
import org.json4s.JsonDSL.WithBigDecimal._
import org.json4s.jackson.JsonMethods._
import org.scalatest.FlatSpecLike
@ServerEndpoint("/WebsocketActorSpec/echoEndpoint")
class EchoEndpoint {
@OnMessage
def onMessage(message: String, session: Session) = message
}
class WebsocketActorSpec extends TestContainer with TestKitBase with FlatSpecLike {
implicit lazy val system = ActorSystem("WebsocketActorSpecSystem")
val serverEndpoint = new EchoEndpoint
val uri = getURI(serverEndpoint.getClass)
"WebsocketActor" should "forward received messages to receiver" in {
val server = startServer(serverEndpoint.getClass)
val actorRef = TestActorRef(WebsocketActor.props(uri))
val probe = TestProbe("probe")
val json = List.empty
val expected = JObject(json)
actorRef ! probe.ref
actorRef ! Connect
actorRef ! compact(render(json))
probe.expectMsgPF() {
case (_: Instant, expected) => true
case _ => false
}
stopServer(server)
}
}
开发者ID:blbradley,项目名称:kafka-cryptocoin,代码行数:47,代码来源:WebsocketActorSpec.scala
示例20: ParsingActorSpec
//设置package包名称以及导入依赖的类
package com.mikemunhall.simpletwitterstats.server
import java.util.Date
import akka.actor.Props
import akka.testkit.{TestActorRef, TestProbe}
import com.mikemunhall.simpletwitterstats.server.ParsingActor.Parse
import com.mikemunhall.simpletwitterstats.server.PersistingActor.Persist
import org.mockito.Mockito.when
import twitter4j.{HashtagEntity, Status, URLEntity}
class ParsingActorSpec extends ActorUnitSpec {
val persistingActorProbe = TestProbe()
val underTest = TestActorRef(Props(new ParsingActor {
override val persistingActor = persistingActorProbe.ref
}))
"The actor" should "create a Tweet from a Status and delegate to the persisting actor" in {
val status = mock[Status]
when(status.getId).thenReturn(12345l)
when(status.getCreatedAt).thenReturn(new Date())
when(status.getText).thenReturn("hi")
when(status.getHashtagEntities).thenReturn(Array[HashtagEntity]())
when(status.getURLEntities).thenReturn(Array[URLEntity]())
underTest ! Parse(status)
val message = persistingActorProbe.expectMsgType[Persist]
message.tweet.id should be (12345l)
}
}
开发者ID:mmunhall,项目名称:simple-twitter-stats,代码行数:33,代码来源:ParsingActorSpec.scala
注:本文中的akka.testkit.TestActorRef类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论