【问题标题】:Testing a method with Akka Actor parameters使用 Akka Actor 参数测试方法
【发布时间】:2017-04-28 02:36:11
【问题描述】:

我有一个任务,我需要对其进行测试。这个任务需要一些actors作为参数,所以我用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)

【问题讨论】:

  • 出于测试目的,强烈建议使用 akka-testkit 模块doc.akka.io/docs/akka/current/scala/testing.html
  • 顺便说一句,@nafr 我不是在测试演员。我正在测试另一种以 Actor 作为参数的方法。
  • “代码没有结束”是什么意思?你如何运行测试(junit,scalatest)?
  • @zella 我认为后台Timer 线程t 正在运行,因为它没有被取消。这是一个测试代码,虽然我没有将它插入测试框架,因为我发现它永远存在。

标签: testing akka actor


【解决方案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)

【讨论】:

    猜你喜欢
    • 2020-10-04
    • 2019-02-12
    • 2012-05-20
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 2013-05-23
    • 2018-03-10
    相关资源
    最近更新 更多