sea*_*ins 14 unit-testing scala akka
当我在Akka中有一个父演员时,在初始化时直接创建一个子actor,当我想为父actor编写单元测试时,如何用TestProbe或mock替换子actor?
例如,使用以下设计的代码示例:
class TopActor extends Actor {
val anotherActor = context.actorOf(AnotherActor.props, "anotherActor")
override def receive: Receive = {
case "call another actor" => anotherActor ! "hello"
}
}
class AnotherActor extends Actor {
override def recieve: Receive = {
case "hello" => // do some stuff
}
}
Run Code Online (Sandbox Code Playgroud)
如果我想为TopActor编写测试,要检查发送给AnotherActor的消息是"hello",我该如何替换AnotherActor的实现?看起来TopActor直接创建了这个子项,因此不容易访问.
sea*_*ins 10
以下方法似乎有效但直接覆盖anotherActor的val似乎有点粗糙.我想知道是否有其他更清洁/推荐的解决方案,这就是为什么我仍然问这个问题,即使我有这个有效的答案:
class TopActorSpec extends MyActorTestSuiteTrait {
it should "say hello to AnotherActor when receive 'call another actor'" {
val testProbe = TestProbe()
val testTopActor = TestActorRef(Props(new TopActor {
override val anotherActor = testProbe.ref
}))
testTopActor ! "call another actor"
testProbe.expectMsg(500 millis, "hello")
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2393 次 |
| 最近记录: |