Akka.net and Unit tests

I would like to use Akka.net TestKit to write unit tests, but I have a question. I have a SubscriptionService class that is responsible for sending messages to selected members.

public class SubscriptionService : ReceiveActor
{
    private readonly ActorSelection service1;

    private readonly ActorSelection service2;

    public SubscriptionService()
    {
        this.service1 = Context.ActorSelection("Service1");
        this.service2 = Context.ActorSelection("Service2");

        this.Receive<RequestMessage>(message => this.ProcessRequestMessage(message));
    }

    private void ProcessRequestMessage(RequestMessage message)
    {
        this.service1.Tell(message);
        this.service2.Tell(message);
    }

      

How can I test this behavior? I created this test, but in this test I am getting an exception. "More information: Assert.Fail failed. Failed: Timeout 00:00:03 pending message"

[TestClass]
public class SubscriptionServiceUnitTests : TestKit
{
    [TestMethod]
    public void Test1()
    {
        var subscriptionServiceRef = this.ActorOfAsTestActorRef<SubscriptionService>("SubscriptionService");

        subscriptionServiceRef.Tell(new RequestMessage());

        var answer = this.ExpectMsg<RequestMessage>();
    }

      

I mean, how can I get the message for service1 and service2 in Test1 method?

+3


source to share


1 answer


ExpectMsg

only works in conjunction with a special type of actor called TestActor

. You can get / create it from a test suite. The role is to catch and verify the sending of messages.

If you change your actor a little SubscriptionService

, you can give him an acting referent. The easiest way to do this is to simply add the refs actor via the actor constructor - I used an interface ICanTell

, which is a more general form, implemented by both actor reflexes and actor choice:

public class SubscriptionService : ReceiveActor
{
    private readonly ICanTell service1;
    private readonly ICanTell service2;

    public SubscriptionService(ICanTell service1, ICanTell service2)
    {
        this.service1 = service1;
        this.service2 = service2;
        this.Receive<RequestMessage>(message => this.ProcessRequestMessage(message));
    }

      



This way you can create your actor using:

Context.ActorOf(Props.Create(() => new SubscriptionService(Context.ActorSelection("Service1"), Context.ActorSelection("Service2")));

      

To test this, in your TestKit spec class, initialize it with TestActor or TestProbe.

+3


source







All Articles