简体   繁体   中英

Unit test akka actor method

I have an actor of the form:


class TestActor(repo: Repo) extends Actor {
  implicit val executionContext: ExecutionContext = context.dispatcher

  def receive: Receive = {
    ...
  }

  def testMethod(stringSeq: Seq[String]): String =
       ...
    }
}

I want to test the method testMethod only.

I am trying to write the test case as:


class TestActorSpec
    extends TestKit(ActorSystem("TestActorSpec"))
    with WordSpecLike
    with Matchers
    with JsonSupport
    with MockitoSugar
    with BeforeAndAfterAll
    with ImplicitSender {
  override def afterAll: Unit = TestKit.shutdownActorSystem(system)

  implicit val futureDuration: FiniteDuration = 60.seconds
  implicit val timeout: Timeout               = 10.seconds
  val mockedRepo               = mock[Repo]

  val testActorRef: ActorRef = system.actorOf(
    TestActor.props(mockedRepo)
  )

  "TestActorSpec" should {
    "be able to get data " in {

    }
  }
}

How can i access the method testMethod from testActorRef?

I also tried:

 TestActorRef[TestActor].underlyingActor.testMethod(Seq("data"))

It does not work for me.

Actors should be tested via messages you send to them. But you still can test methods in isolation if the method is not accessing any actor specific values, like context .

You can move testMethod into companion object and test it from there.


class TestActor(repo: Repo) extends Actor {
  implicit val executionContext: ExecutionContext = context.dispatcher

  def receive: Receive = {
//    call  TestActor.testMethod
  }

}

object TestActor {
  def testMethod(stringSeq: Seq[String]): String = ???
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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