【问题标题】:How to make sure an Akka actor is alive and subscribed to the eventstream如何确保 Akka 演员是活着的并订阅了事件流
【发布时间】:2016-12-15 00:50:21
【问题描述】:

我正在尝试在 java 中测试 Akka Actor。这就是测试要做的,代码如下

  • 这个被测actor在其构造函数中订阅了偶数流。
  • actor 是在测试中使用 actorsystem 上的普通 actorOf 创建的。
  • 这会返回一个 ActorRef,但真正的演员是在幕后异步创建的。
  • 我在测试中的事件流上发布了一条消息。
  • 但是,由于 Actor 是异步构造的,因此在 Actor 将自己订阅到事件流之前,消息会在事件流上发布。
  • 结果:被测参与者永远不会看到消息,并且神经元将其转发给他应该将消息转发给的参与者。测试失败,因为要转发到的参与者是该测试中的一个测试探针,我们希望消息在该测试探针上到达。

在将消息发布到事件流之前,我可以休眠或等待片刻,但是是否有一种“更简洁”的方式来检查参与者是否已完全启动并运行?我可以在事件流上监听一些事件,告诉我演员已经完成了自己的创作吗?

@Test
public void testListenOnEventStreamAndForward() throws InterruptedException
{
    // given
    final TestProbe actorToForwardMessageTo = new TestProbe(this.actorSystem);
    final Function<ActorRefFactory, ActorRef> actorToForwardMessageTosFactoryFunction = (actorRefFactory) -> actorToForwardMessageTo.ref();
    this.actorSystem.actorOf(Props.create(ActorUnderTest.class, () -> new ActorUnderTest(actorToForwardMessageTosFactoryFunction)));

    //The test is green, depending on the whether we sleep here or not
    //Thread.sleep(1000);

    // when
    this.eventStream.publish("someStringMessageTheActorUnderTestShouldPickUp");

    // then
    actorToForwardMessageTo.expectMsg("someStringMessageTheActorUnderTestShouldPickUp");
}


private static class ActorUnderTest extends AbstractActor
{

    public ActorUnderTest(final Function<ActorRefFactory, ActorRef> actorToForwardMessageToFactoryFunction) throws Exception
    {
        context().system().eventStream().subscribe(self(), String.class);
        final ActorRef actorToForwardMessageTo = actorToForwardMessageToFactoryFunction.apply(getContext());

        receive(ReceiveBuilder
                .match(
                        String.class,
                        stringMessage -> actorToForwardMessageTo.tell(stringMessage, self()))
                .matchAny(
                        message -> unhandled(message))
                .build());
    }

}

【问题讨论】:

  • 如果您在测试中使用resolveOne 函数会怎样?
  • resolveOne 在 actorPath 上工作,如果我没记错的话。我只有 actorRef 可用。

标签: java unit-testing akka


【解决方案1】:

您可以使用awaitAssert 重试发布/期待消息,直到超时,然后再失败。请参阅此处文档中的 awaitAssert 部分:http://doc.akka.io/docs/akka/2.4/java/testing.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    相关资源
    最近更新 更多