Akka中的单元测试 – TestKit
在任何一个系统中,测试代码都是至关重要的。当一个系统不断增大的时候,跟需要有每个关键功能的测试代码。在这片文章中,我将简要介绍一下Actor(Akka)模型中的测试方法和测试思想。
本文所有使用的代码来自于Akka的官方文档。
基本思想
ScalaTest
首先,Akka的测试是基于ScalaTest的,所以我们首先介绍一下Scala的测试方法。
Scala的测试使用的是WordSpecLike
模式,使用3个关键字组织测试–must
, should
, can
。这3个关键字可以创建一个测试,之后使用in
关键字可以进行多个子测试(单元测试)。下面给一个例子:
"An Echo actor" must{
"send back message unchanged" in {
val echo = system.actorOf(TestActors.echoActorProps)
echo ! "hello world"
expectMsg("hello world")
}
"another result" in {
// another case
...
}
}
must
关键字创建了一个测试—An Echo actor
,之后有一个单元测试send back message unchanged
,在之后还可以创建其他条件下的测试。使用WordSpecLike
的测试模式,测试的可读性非常好。
TestKit
进行Actor实验,最为关键就是要扩展TestKit
类。需要下面两个依赖
"com.typesafe.akka" %% "akka-testkit" % akkaVersion,
"org.scalatest" %% "scalatest" % "3.0.1",
首先,我们需要知道TestKit
中,有一个system
变量 – ActorSystem
。我们创建新的Actor的时候,都需要使用system
。
我们会产生一个疑问,如果我们向一个测试Actor – toTestActor 发送不同类型消息,查看toTestActor的处理结果,我们使用哪个Actor发送消息给toTestActor,并使用这个Actor接收来自toTestActor呢?
在TestKit中保存着一个testActor变量,这个变量会发送消息给toTestActor。
同时,testActor接收到的消息,会保存到一个queue
中,我们调用expectMsg
方法,检查queue
中的是否有我们想要的消息。
举个例子:
"An Echo actor" must{
"send back message unchanged" in {
val echo = system.actorOf(TestActors.echoActorProps)
echo ! "hello world"
expectMsg("hello world")
}
}
在这个例子中,我们使用system
创建了一个Actor – echo
进行测试。我们向echo
发送消息(使用的是testActor
),并使用expectMsg
等待消息回复。
测试方法
断言方法
在之前的例子中,我们使用了expectMsg
这个断言。在Akka中,有许多不同的断言方法,这里列出以下:
* expectMsg[T](d: Duration, msg:T)
:等待一段时间,检查消息
* expectNoMsg(d: Duration)
:无消息返回
等待时间
使用within([min, ]max{}
设定一段时间来执行代码段中的代码。例子:
"Time wait" should {
"not fail" in {
within(200 millis){
// expectNoMsg or receiveWhile, the final check for the within
// is skipp