由于我目前正在为我的Akka应用程序编写测试用例(http://doc.akka.io/docs/akka/snapshot/scala/testing.html),我想知道是否有办法测试一个actor的接口。我的意思是,我想检查目标actor的 receive 方法是否处理消息 A 或否。想象一下以下场景:
演员A可以处理消息b和c。演员B希望将mesage b和a发送给演员A.为了确保这很好用,我想编写一个测试用例,确保演员A正在处理消息a和b。
答案 0 :(得分:9)
这取决于你想要测试的内容。
由于receive
方法是PartialFunction
,您可以执行isDefinedAt
测试,如下所示:
$ sbt test:console
scala> import akka.actor._
scala> import akka.testkit._
scala> class MyActor extends Actor {
def receive = {
case n: Long => println("Got %d".format(n))
case s: String => println("Got %s".format(s))
}
}
scala> implicit val system = ActorSystem()
system: akka.actor.ActorSystem = akka://default
scala> val myActor = TestActorRef[MyActor]
myActor: akka.testkit.TestActorRef[MyActor] = TestActor[akka://default/user/$$a]
scala> val underlying = myActor.underlyingActor
underlying: MyActor = MyActor@365d7762
scala> underlying.receive.isDefinedAt(123L)
res0: Boolean = true
scala> underlying.receive.isDefinedAt("banana")
res1: Boolean = true
scala> underlying.receive.isDefinedAt(true)
res2: Boolean = false
scala> underlying.receive.isDefinedAt(123)
res3: Boolean = false
scala> underlying.receive.isDefinedAt(null)
res4: Boolean = false
scala> system.shutdown()