【问题标题】:How to create a TestActorRef inside a test class for an Actor with constructor params?如何在测试类中为具有构造函数参数的 Actor 创建 TestActorRef?
【发布时间】:2015-03-10 15:14:19
【问题描述】:

如何在测试类中创建 TestActorRef。具体来说,我有以下测试设置...

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

...当我运行测试时,一切都通过了,但是在关闭 ActorSystem 后,我得到了这个很长的错误跟踪...

[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

我遇到了this 上一个问题,但在这种情况下,接受的答案对我不起作用。

如果相关,这里是 DoubleAuctionMarket 演员的定义...

class DoubleAuctionMarket(val security: Security, val ticker: Agent[Tick]) extends Actor with ActorLogging {
  this: MatchingEngine =>
  ...

【问题讨论】:

  • 你的DoubleAuctionMarket演员是如何定义的?
  • 我已更新问题以包含有关 DoubleAuctionMarket 参与者的信息。
  • 你试过没有BasicMatchingEngine的'on the fly' mixin吗?我认为您的代码和TestActorRef 的使用没有任何问题。
  • 抱歉,但我对 Scala 和 Akka 都是新手。 “没有'on the fly' mixin”到底是什么意思?
  • 这种自我类型引用限制(this:MatchingEngine =>)通常保留给特征,以确保它们只混合到某些类型的类中。你想通过DoubleAuctionMarket 上的设置来完成什么?在课堂上这样做会迫使您在实例化时进行动态混合,我认为这是您问题的根源。

标签: scala akka akka-testkit


【解决方案1】:

我遇到了同样的问题,因为我使用伴随对象将配置注入 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))

我会尝试像 vptheron 所说的那样删除with BasicMatchingEngine,使用构造函数而不混合其他任何东西。如果这还不够,也可以尝试使用更少的参数。

这必须解决您的问题,因为 just 没有问题:

TestActorRef(new DoubleAuctionMarket(google, ticker))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    相关资源
    最近更新 更多