Akka.net和单元测试

本文关键字:单元测试 net Akka | 更新日期: 2023-09-27 18:00:06

我想使用Akka.net TestKit来编写单元测试,但我有一个问题。我有一个类SubscriptionService,它负责向选定的参与者传输消息。

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);
    }

我如何测试这种行为?我创建了这个测试,但在这个测试中我得到了异常。"附加信息:断言。失败。失败:等待消息时超时00:00:03"

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

我的意思是,我如何在Test1方法中获得service1和service2的消息?

Akka.net和单元测试

ExpectMsg只有在与一种称为TestActor的特殊演员组合时才有效。您可以从测试套件访问/创建它。它的作用是捕获并验证发送给它的消息

如果你稍微重新设计一下SubscriptionService actor,你可以将测试actor refs传递给它。最简单的方法是简单地通过actor构造函数注入actor ref-我使用了ICanTell接口,这是一种更通用的形式,由actor ref和actor selection实现:

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));
    }

通过这种方式,您可以使用创建您的演员

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

要测试它,请在TestKit规范类中使用TestActor或TestProbe初始化它。