使用Akka Actor参数测试方法

时间:2017-04-28 02:36:11

标签: testing akka actor

我有一项任务,我需要测试。此任务将某些actor作为参数,因此我使用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)

1 个答案:

答案 0 :(得分:1)

正如@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)这是测试某些东西的唯一真实方式,演员参与其中 2)使用TestKit.shutdownActorSystem(system)