3

我想使用 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);
    }

我该如何测试这种行为?我创建了这个测试,但在这个测试中我得到了异常。“附加信息:Assert.Fail 失败。失败:等待消息时超时 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 的消息?

4

1 回答 1

3

ExpectMsg仅在与称为TestActor. 您可以从测试套件访问/创建它。它的作用是捕获并验证发送给它的消息。

如果你SubscriptionService稍微重新设计你的actor,你可以将测试actor refs 传递给它。最简单的方法是通过actor构造函数简单地注入actor refs - 我使用ICanTell了接口,这是更通用的形式,由actor refs和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 对其进行初始化。

于 2015-06-28T19:32:36.230 回答