Dan*_*ier 3 testing unit-testing scala actor akka
我有一个akka演员:
class MyActor extends Actor {
def recieve { ... }
def getCount(id: String): Int = {
//do a lot of stuff
proccess(id)
//do more stuff and return
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试为getCount方法创建单元测试:
it should "count" in {
val system = ActorSystem("Test")
val myActor = system.actorOf(Props(classOf[MyActor]), "MyActor")
myActor.asInstanceOf[MyActor].getCount("1522021") should be >= (28000)
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用:
java.lang.ClassCastException: akka.actor.RepointableActorRef cannot be cast to com.playax.MyActor
Run Code Online (Sandbox Code Playgroud)
我该如何测试这种方法?
做这样的事情:
import org.scalatest._
import akka.actor.ActorSystem
import akka.testkit.TestActorRef
import akka.testkit.TestKit
class YourTestClassTest extends TestKit(ActorSystem("Testsystem")) with FlatSpecLike with Matchers {
it should "count plays" in {
val actorRef = TestActorRef(new MyActor)
val actor = actorRef.underlyingActor
actor.getCount("1522021") should be >= (28000)
}
}
Run Code Online (Sandbox Code Playgroud)
我通常建议将由Actor执行的任何"业务逻辑"分解为一个单独的类,该类作为构造函数参数提供或通过Cake组件提供.这样做简化了Actor,只留下了保护长期可变状态和处理传入消息的责任.它还有助于测试业务逻辑(通过使其单独用于单元测试)以及Actor如何通过在测试Actor本身时提供模拟/间谍实例或组件来与该逻辑交互.
| 归档时间: |
|
| 查看次数: |
1530 次 |
| 最近记录: |