【问题标题】:How to test a public method in an akka actor?如何在 akka 演员中测试公共方法?
【发布时间】:2014-03-25 23:33:39
【问题描述】:

我有一个 akka 演员:

class MyActor extends Actor {
  def recieve { ... }

  def getCount(id: String): Int = {
    //do a lot of stuff
    proccess(id)
    //do more stuff and return
  }
}

我正在尝试为 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)
}

但它不起作用:

  java.lang.ClassCastException: akka.actor.RepointableActorRef cannot be cast to com.playax.MyActor

我该如何测试这个方法?

【问题讨论】:

    标签: scala unit-testing testing akka actor


    【解决方案1】:

    做这样的事情:

    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)
      }
    }
    

    【讨论】:

      【解决方案2】:

      我通常建议将任何由 Actor 执行的“业务逻辑”分解到一个单独的类中,该类作为构造函数参数提供或通过 Cake 组件提供。这样做可以简化 Actor,只留下保护长期可变状态和处理传入消息的责任。它还有助于测试业务逻辑(通过使其单独可用于单元测试)以及通过在测试 Actor 本身时提供模拟/间谍实例或组件来测试 Actor 如何与该逻辑交互。

      【讨论】:

      • 这也是一个很好的答案,但并不总是可能的。例如,我的 PersistentActor 子类的重写 persistenceId 方法。要测试该方法,您将需要底层参与者。
      猜你喜欢
      • 2014-03-09
      • 2016-02-03
      • 2015-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-29
      • 2020-08-28
      相关资源
      最近更新 更多