简体   繁体   English

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

[英]How to test a public method in an akka actor?

I have an akka actor: 我有一个akka演员:

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

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

I am trying to create a unit test for the getCount method: 我正在尝试为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)
}

But it is not working: 但它不起作用:

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

How could I test this method? 我该如何测试这种方法?

Do something like this: 做这样的事情:

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

I generally recommend factoring any "business logic" that is executed by an Actor into a separate class that is supplied as a constructor parameter or provided via a Cake component. 我通常建议将由Actor执行的任何“业务逻辑”分解为一个单独的类,该类作为构造函数参数提供或通过Cake组件提供。 Doing this simplifies the Actor, leaving it only the responsibility to protect long-lived mutable state and handle incoming messages. 这样做简化了Actor,只留下了保护长期可变状态和处理传入消息的责任。 It also facilitates testing both the business logic (by making it separately available for unit tests) and how the Actor interacts with that logic by supplying a mock / spy instance or component when testing the Actor itself. 它还有助于测试业务逻辑(通过使其单独用于单元测试)以及Actor如何通过在测试Actor本身时提供模拟/间谍实例或组件来与该逻辑交互。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM