MessagingSleuthOperators 在测试期间失败(beanFactory 为空)

MessagingSleuthOperators fails during test (beanFactory is null)

我有一个 spring 启动应用程序,它使用 sleuth 进行消息跟踪,在我的代码中我使用方法

MessagingSleuthOperators.withSpanInScope(beanFactory, message, unused -> {
            doSomething(...);
        });

在测试期间,我想调用我周围的逻辑来测试它的功能。不幸的是,sleuthOperators 调用因 NullPointerException 而崩溃,因为 beanFactory 为空(这是有道理的,因为我没有在我的单元测试中加载上下文)。

有没有办法模拟这个 beanFactory 仍然能够调用 sleuth operators?有没有不使用更容易模拟的运算符的解决方法?

您可以创建 BeanFactory 的静态实例,即 StaticListableBeanFactory。不过,您必须用缺少的豆子来填充它。 StaticListableBeanFactoryaddBean 方法,你可以在其中添加 bean(我猜这些可能是模拟的)。

示例https://github.com/spring-cloud/spring-cloud-sleuth/blob/602749a8d148c281e9f519a1ef362744eeff1f44/spring-cloud-sleuth-instrumentation/src/test/java/org/springframework/cloud/sleuth/instrument/kafka/TracingKafkaProducerTest.java#L81-L86