当前位置: 首页 > 知识库问答 >
问题:

如何在测试类中为具有构造函数参数的执行元创建TestActorRef?

黄君博
2023-03-14
class MatchingEngineSpec extends TestKit(ActorSystem("Securities-Exchange"))
  with FeatureSpecLike
  with GivenWhenThen
  with Matchers {

  val google = Security("GOOG")

  val ticker = Agent(Tick(google, None, None, None))

  val marketRef = TestActorRef(new DoubleAuctionMarket(google, ticker) with BasicMatchingEngine)

  val market = marketRef.underlyingActor
[ERROR] [03/10/2015 15:07:55.571] [Securities-Exchange-akka.actor.default-dispatcher-4] [akka://Securities-Exchange/user/$$b]     Could not instantiate Actor
Make sure Actor is NOT defined inside a class/trait,
if so put it outside the class/trait, f.e. in a companion object,
OR try to change: 'actorOf(Props[MyActor]' to 'actorOf(Props(new MyActor)'.
akka.actor.ActorInitializationException: exception during creation
class DoubleAuctionMarket(val security: Security, val ticker: Agent[Tick]) extends Actor with ActorLogging {
  this: MatchingEngine =>
  ...

共有1个答案

欧阳杰
2023-03-14

我也遇到了同样的问题,因为我使用了一个伴奏对象将配置注入到MyActor中,而没有显式传递它:

object MyActor {
  def apply(): MyActor = new MyActor(MyActorConfig.default)
  val props = Props(new MyActor(MyActorConfig.default))
}

然后我就可以做:

val myActorRef = system.actorOf(MyActor.props, "actorName")

错误与在这里的测试中显式传递参数有关:

TestActorRef(new DoubleAuctionMarket(google, ticker))
TestActorRef(new DoubleAuctionMarket(google, ticker))
 类似资料: