Testing Akka.NET's Context.Parent with TestKit

1.6k views Asked by At

I have an actor that responds to a message by sending a message to it's parent, like this...

public void Handle(string message)
{
    Context.Parent.Tell("Hello");
}

I now want to test that the message is sent to the Actors Parent, but can't figure out how. My current test looks like the following...

pubilc void AllResponsesWillGoToParent()
{
    ActorOf<MyActor>().Tell("Respond to parent");

    ExpectMsg<string>(x => x == "Hello");
}

This of course doesn't work because the actors parent is the test ActorSystem and not the actor assigned to the TestActor property.

Does anyone know how I can test that the message is indeed sent to it's Parent, thanks.

2

There are 2 answers

2
Alexander Prooks On BEST ANSWER

One option to solve this is to create fake parent, that is creating a real child actor that you are testing. This parent will forwarding message from child to a test probe or to TestActor itself.

more patterns here http://hs.ljungblad.nu/post/69922869833/testing-parent-child-relationships-in-akka let me know if you will need a c# snippet

0
AndrewS On

You can solve this by creating the actor you want as a TestActorRef, and then setting the TestActor as its supervisor. This lets you use all the built-in semantics of the TestActor such as ExpectMsg<>.

(For further reference, suggest you check out this guide to unit testing Akka.NET actors that I wrote.)

You could do that like so (using NUnit):

using System;
using Akka.Actor;
using Akka.TestKit.NUnit;
using NUnit.Framework;

namespace ParentTestExample
{
    public class ParentGreeter : ReceiveActor
    {
        public ParentGreeter()
        {
            Receive<string>(s => string.Equals(s, "greet parent"), s =>
            {
                Context.Parent.Tell("Hello parent!");
            });
        }
    }

    [TestFixture]
    public class ParentGreeterSpecs : TestKit
    {
        [Test]
        public void Parent_greeter_should_greet_parent()
        {
            Props greeterProps = Props.Create(() => new ParentGreeter());
            // make greeter actor as child of TestActor
            var greeter = ActorOfAsTestActorRef<ParentGreeter>(greeterProps, TestActor);
            greeter.Tell("greet parent");

            // TestActor captured any message that came back
            ExpectMsg("Hello parent!");
        }
    }
}