Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Akka: testing actor got message

Tags:

akka

scalatest

I have the next code:

//TestActor got some message  
class TestActor extends Actor {

  def receive = {
    case string: String => //.... 
  }
}
//TestReg when create get ActorRef, when i call `pass` method, then should pass text to ActorRef
class TestReg(val actorRef: ActorRef) {
  def pass(text: String) {
   actorRef ! text
  }
}

When i wrote test:

class TestActorReg extends TestKit(ActorSystem("system")) with ImplicitSender
   with FlatSpecLike with MustMatchers with BeforeAndAfterAll {

   override def afterAll() {
     system.shutdown()
   }

   "actorReg" should "pass text to actorRef" in {
      val probe = TestProbe()

      val testActor = system.actorOf(Props[TestActor])

      probe watch testActor

      val testReg = new TestReg(testActor)
      testReg.pass("test")

      probe.expectMsg("test")
   }
}

I got error:

java.lang.AssertionError: assertion failed: timeout (3 seconds) during expectMsg while waiting for test

How to check what the actor got a text?

like image 976
lito Avatar asked Nov 16 '13 07:11

lito


2 Answers

probe.expectMsg() is calling the assertion on the probe. But you passed the testActor into your TestReg class

change it to the following line and it will work

val testReg = new TestReg(probe.ref) 

have to call .ref to make the probe into an ActorRef And you want to do it here not at the instantiation of the variable to avoid certain bugs that are outside of the scope of this response

the error in the logic as I see it is you are thinking that the watch method makes probe see what test actor does. but its death watch not message watch. which is different.

like image 180
Dante Romero Avatar answered Nov 20 '22 18:11

Dante Romero


Create application.conf file with this:

akka {
  test {
    timefactor = 1.0    
    filter-leeway = 999s
    single-expect-default = 999s
    default-timeout = 999s

    calling-thread-dispatcher {
      type = akka.testkit.CallingThreadDispatcherConfigurator
    }
  }

  actor {
    serializers {
      test-message-serializer = "akka.testkit.TestMessageSerializer"
    }

    serialization-identifiers {
      "akka.testkit.TestMessageSerializer" = 23
    }

    serialization-bindings {
      "akka.testkit.JavaSerializable" = java
    }
  }
}
like image 35
Dmitry Kaltovich Avatar answered Nov 20 '22 18:11

Dmitry Kaltovich