我有一个任务,我需要测试它。此任务将一些参与者作为参数,因此我使用 TestActor
创建了一个测试,如下所示:
几个问题:
1. 为测试目的创建 ActorSystem
是正常做法吗?
2.代码没有结束。我试过了
val system = ActorSystem("TestRoutingSystem")
val actorRef = system.actorOf(Props(new TestActor), name = "testActor")
var poisonReceived = false
var workReceived = 0
class TestActor extends Actor with Logging {
def receive = {
case msg: WorkerMessage =>
workReceived += 1
case x: Boolean => {
poisonReceived = true
}
}
}
val t = new java.util.Timer()
val task = new TestTask(...)
task.run()
t.schedule(task, 10, 10)
system.shutdown()
Thread.sleep(150)
println(poisonReceived )
println(workReceived)
最佳答案
正如@nafr所说,最好使用akka-testkit
我不熟悉 scalatest,所以我用 junit 风格写了例子。例如,我们应该测试一些类,它向 actor 发送两条消息:
class TimerTask(actorRef: ActorRef) {
def run(): Unit = {
actorRef ! "some msg"
actorRef ! "some other msg"
}
}
完整的测试看起来像这样:
import akka.actor.{ActorRef, ActorSystem}
import akka.testkit.{TestKit, TestProbe}
import org.junit.{After, Before, Test}
class TestExample {
protected implicit var system: ActorSystem = _
@Before
def setup(): Unit = {
system = ActorSystem.create("test")
}
@After
def tearDown(): Unit = {
TestKit.shutdownActorSystem(system)
}
@Test
def example(): Unit = {
val testProbe = TestProbe()
val source = new TimerTask(testProbe.ref)
source.run()
testProbe.expectMsg("some msg")
testProbe.expectMsg("some other msg")
}
}
所以关于你的问题的答案:
1) 这是唯一真实的测试方法, Actor 参与
2) 使用 TestKit.shutdownActorSystem(system)
关于使用 Akka Actor 参数测试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43671046/