A query on testing actors

(Mghildiy) #1

In code:

public void testReplyWithEmptyReadingIfNoTemperatureIsKnown() {
TestKit probe = new TestKit(system);
ActorRef deviceActor = system.actorOf(Device.props(“testDevice”, “testGroup”));
deviceActor.tell(new Device.ReadTemperature(1001), probe.getRef());
Device.RespondTemperature response = probe.expectMsgClass(Device.RespondTemperature.class);
assertEquals(1001, response.requestId);
assertEquals(Optional.empty(), response.reading);

If I replace probe.getRef() with deviceActor, test fails.
Why this happens? Is it wrong way of dealing with actors?

(Johan Andrén) #2

The second parameter to tell is the sender, so by passing the probe.getRef(), any message the actor sends back to sender() will end up in the probe which is why you can assert that you got a response with probe.expectMsgClass on the next line. If you put some other ActorRef there the response will be sent to that actor instead.

(Mghildiy) #3

So can an actor send message to itself?

(Johan Andrén) #4

Yes it can.

I’d recommend that you work through the getting started guide in the docs to get a hang of the basics: https://doc.akka.io/docs/akka/current/guide/index.html