How to create a TestActorRef inside a test class f

2019-06-10 00:14发布

问题:

How does one create a TestActorRef inside a test class. Specifically, I have the following test set up...

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

...when I run the tests everything passes, but after shutting down the ActorSystem I get this long error trace...

[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

I came across this previous question, but the accepted answer didn't work for me in this case.

In case it is relevant, here is the definition of the DoubleAuctionMarket actor...

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

回答1:

I had the same issue because I was using a companion object to inject the config into MyActor without passing it explicitly:

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

Then I can just do:

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

The error is related to passing the arguments explicitly in the test here:

TestActorRef(new DoubleAuctionMarket(google, ticker))

I would try to remove the with BasicMatchingEngine as vptheron said, use the constructor without mixing anything else. Try also with an argument less actor if that is not enough.

That must fix your problem since there are no issues with just:

TestActorRef(new DoubleAuctionMarket(google, ticker))