如何在akka actor中测试公共方法?

3

我有一个Akka Actor:

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

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

我正在尝试为getCount方法创建单元测试:

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

我该如何测试这个方法?
2个回答

9

可以这样做:

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

6

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


这也是一个不错的答案,但并非总是可行。例如,我子类的PersistentActor覆盖了persistenceId方法。要测试该方法,您将需要底层的actor。 - Brian Ensink

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接