Akka Actor Test: automatic response using TestProbe

I am trying to get a test study to respond with a confirmation whenever it receives any message.

In my test, I wrote the following code, but it does not work:

val chgtWriter = new TestProbe(system)  {

          def receive: Receive = {

            case m => println("receive messagereplying with ACK"); sender() ! ACK

          }

        }

Is there any way to do this. An actor actually sending a message to a test probe definitely works in a different thread than TestThread. Below you can see the full test, as currently created.

feature("The changeSetActor periodically fetch new change set following a schedule") {


scenario("A ChangeSetActor fetch new changeset from a Fetcher Actor that return a full and an empty ChangeSet"){


  Given("a ChangeSetActor with a schedule of fetching a message every 10 seconds, a ChangeFetcher and a ChangeWriter")

    val chgtFetcher = TestProbe()

    val chgtWriter = new TestProbe(system)  {

      def receive: Receive = {

        case m => println("receive message {} replying with ACK"); sender() ! ACK

      }

    }
    val fromTime = Instant.now().truncatedTo(ChronoUnit.SECONDS)
    val chgtActor = system.actorOf(ChangeSetActor.props(chgtWriter.ref, chgtFetcher.ref, fromTime))

  When("all are started")


  Then("The Change Fetcher should receive at least 3 messages from the ChangeSetActor within 40 seconds")

    var changesetSNum = 1

    val received = chgtFetcher.receiveWhile( 40 seconds) {

      case FetchNewChangeSet(m) => {

        println(s"received: FetchNewChangeSet(${m}")

        if (changesetSNum == 1) {
            chgtFetcher.reply(NewChangeSet(changeSet1))
            changesetSNum += 1
          }
          else
            chgtFetcher.reply(NoAvailableChangeSet)
        }

      }

    received.size should be (3)

}

}

ChangeSetActor is fully tested and working. Test freezes with ChangeWriter. It never receives a message in a receive method.

EDIT1 (after @Jakko anser)

Autopilots :

val probe = TestProbe()
probe.setAutoPilot(new TestActor.AutoPilot {
  def run(sender: ActorRef, msg: Any): TestActor.AutoPilot =
    msg match {
      case "stop" ⇒ TestActor.NoAutoPilot
      case x      ⇒ **testActor.tell(x, sender)**; TestActor.KeepRunning
    }
})

, , , , , "testActor". testActor? .

+4
1

script . :

import akka.testkit._
val probe = TestProbe()
probe.setAutoPilot(new TestActor.AutoPilot {
  def run(sender: ActorRef, msg: Any): TestActor.AutoPilot = {
    println("receive messagereplying with ACK")
    sender ! ACK
    TestActor.KeepRunning
  }
})

Auto Pilot. , . .

, , , . , (TestActor.KeepRunning), (TestActor.NoAutoPilot). .

, , , .

testActor , . , ChangeSetActor, chgtActor. , , , , testActor.

+3

Source: https://habr.com/ru/post/1650239/


All Articles