我有一个函数,它使用scheduleOnce来安排将来某个时间发生的事件,我想编写一个测试来检查:
但我不想让考试等几分钟什么也不做。
如何最好地测试使用akka的Scheduler的代码?
发布于 2014-11-14 13:16:29
下面是@lmm描述的模拟调度程序的示例。在这个例子中,我们真正地测试了作为两个不同场景的动作的完整调度和处理。给出某种条件的第一个测试(在我的示例中接收到某种类型的消息),我们将安排一个回调,第二个测试是处理在定时器关闭时被触发回self的消息。守则如下:
object TimerExampleActor{
case object ClearState
case class ScheduleStateClearing(duration:FiniteDuration)
}
class TimerExampleActor extends Actor{
import TimerExampleActor._
var state:List[Int] = Nil
def receive = {
case ScheduleStateClearing(d) =>
scheduler.scheduleOnce(d, self, ClearState)(context.dispatcher)
case ClearState =>
state = Nil
}
def scheduler = context.system.scheduler
}然后,使用specs2和mockito,我的测试用例如下:
class TimerExampleActorTest extends Specification with Mockito with NoTimeConversions{
import TimerExampleActor._
implicit val system = ActorSystem("test")
trait testscope extends Scope{
val mockScheduler = mock[Scheduler]
val actor = TestActorRef(new TimerExampleActor{
override def scheduler = mockScheduler
})
}
"A request to schedule state clearing" should{
"schedule a callback for the message ClearState to self with the supplied duration" in new testscope{
val dur = 1.minute
actor ! ScheduleStateClearing(dur)
there was one(mockScheduler).scheduleOnce(dur, actor, ClearState)(actor.underlyingActor.context.dispatcher)
}
}
"A ClearState message received by the actor" should{
"clear the interval 'state' List" in new testscope{
actor.underlyingActor.state = List(1,2,3)
actor ! ClearState
actor.underlyingActor.state mustEqual Nil
}
}
}您可以看到,当我创建测试中的参与者实例时,我重写了我创建的方法,以获取调度器的实例,允许我返回一个模拟。这并不是进行这样的测试的唯一方法,但这肯定是您需要考虑的一种选择。
发布于 2014-11-14 10:46:56
使调度程序接受一个时间参数。在测试中,使用比常规代码更短的时间。
或者..。在测试时,您可以混合一种特殊的特性,根据需要修改类(缩短等待时间)。
https://stackoverflow.com/questions/26920241
复制相似问题