Akka. How to taunt child actors in java?

Let's say I have a parent actor who creates the actor himself.

public static class Parent extends UntypedActor {

private ActorRef child = context().actorOf(Props.create(Child.class));

    @Override
    public void onReceive(Object message) throws Exception {
        // do some stuff
        child.tell("some stuff", self());
    }
}

public static class Child extends UntypedActor {

    @Override
    public void onReceive(Object message) throws Exception {

    }
}

How can I mock this kid? Google did not give me any reasonable results. I was told that the Akka documentation that creating an actor is good practice. But how can I follow this practice if I can’t even test my actors?

+4
source share
2 answers

I use probes as described in this answer to a similar question:

How to taunt Actors with a child to test the Akka system?

ActorSystem system = ActorSystem.create();

new JavaTestKit( system )
{{
  final JavaTestKit probe = new JavaTestKit( system );
  final Props props = Props.create( SupervisorActor.class );

  final TestActorRef<SupervisorActor> supervisorActor =
    TestActorRef.create( system, props, "Superman" );

  supervisorActor.tell( callCommand, getTestActor() );

  probe.expectMsgEquals(42);
  assertEquals(getRef(), probe.getLastSender());
}};
0
source

Scala, , Java. , TestProbe . :

import akka.actor.{Actor, Props}

class Parent extends Actor {
  import Parent._

  val child = context.actorOf(Child.props)

  override def receive: Receive = {
    case TellName(name) => child ! name
    case Reply(msg) => sender() ! msg
  }
}

object Parent {
  case class TellName(name: String)
  case class Reply(text: String)
  def props = Props(new Parent)
}

class Child extends Actor {
  override def receive: Actor.Receive = {
    case name: String => sender !  Parent.Reply(s"Hi there $name")
  }
}

object Child {
  def props = Props(new Child)
}

, Parent, TellName Child. Child , Reply - ", ". :

class ParentSpec extends TestKit(ActorSystem("test")) with WordSpecLike with Matchers with ImplicitSender {


  val childProbe = TestProbe()

  "Parent actor" should {
    "send a message to child actor" in {
      childProbe.setAutoPilot(new AutoPilot {
        override def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
          case name: String => sender ! Reply(s"Hey there $name")
            NoAutoPilot
        }
      })
      val parent = system.actorOf(Props(new Parent {
        override val child = childProbe.ref
      }))
      parent ! TellName("Johnny")
      childProbe.expectMsg("Johnny") // Message received by a test probe
      expectMsg("Hey there Johnny") // Reply message
    }
  }
}

, Child, setAutoPilot, , . , , Child "", Reply, ", " . TellName "". , - - childProbe.expectMsg("Johnny"). - expectMsg("Hey there Johnny"). , ", " , ", " , , Child.

0

All Articles