【问题标题】:Check for lack of log messages when testing akka actors在测试 akka actor 时检查是否缺少日志消息
【发布时间】:2019-04-29 18:58:52
【问题描述】:

在使用 TestKit 测试 Akka Actor 时,https://doc.akka.io/docs/akka/2.5/testing.html 显示如何验证给定消息是否已记录。

有没有办法检查是否缺少消息?

我让我的演员设置为在收到未处理的消息时调用一个方法来记录“收到意外消息”之类的日志。在我的测试中,我想验证该消息从未被记录,即使测试似乎成功了。有没有办法做到这一点?

我正在使用 Akka 2.5 和 Java 10。

【问题讨论】:

    标签: java akka


    【解决方案1】:

    这取决于您的实施。你可以做以下两件事之一:

    1) 创建一个 TestKit 探针并使其订阅系统的 eventStream

    yourActorSystemInTheTest.eventStream().subscribe(yourProbe.getRef(), UnhandledMessage.class);

    然后在最后检查探测收到了多少条消息,在您的情况下为 0。使用您可以使用的众多“预期...”方法之一。

    2) 文档告诉您如何检查日志消息,因此只需断言您收到“收到意外消息”的次数为 0。

    同样,根据您的演员的实施,上述方法可能不起作用。

    祝你好运!

    【讨论】:

    • 这似乎会导致所有的日志消息都被抑制。我会怎么做才能让消息既检查消息又出现在他们通常的位置。我在 application.conf 中尝试了akka.loggers = [akka.testkit.TestEventListener, "akka.event.Logging$DefaultLogger" ],但没有成功。
    • 忽略前面的评论:日志消息确实显示在预期的位置。
    【解决方案2】:

    为了提供一些细节,这是我需要做的:

    import akka.event.Logging;
    import akka.testkit.javadsl.EventFilter;
    import akka.testkit.javadsl.TestKit;
    ...
    
    @Test
    public void noUnhandledTest() {
    
      new TestKit(system) {{
        new EventFilter(Logging.Warning.class, system).
           occurrences(0).
           matches("unhandled event").
           intercept(() -> {
             try {
               <actual test code>
    
               // Intercept needs a supplier
               return 0;
             } catch (Exception e) {
               // Suppliers can't throw
               throw new RuntimeException(e);
             }
           });
      }};
    }
    

    src/test/resources/application.conf:

    akka.loggers = [akka.testkit.TestEventListener ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-08
      • 2018-07-02
      • 2015-05-29
      • 1970-01-01
      • 2013-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多