如何在 Kotlin 中进行方法检测——但要使其方法可测试

How to do method instrumentation in Kotlin - but keep it method testable

我有一个方法需要检测以调用 New Relic:设置一个段,运行 业务逻辑并结束该段。有没有办法在 Kotlin 中做到这一点(如 Spring AOP)?

fun saveCustomer() {
   val segment = NewRelic.getAgent().transaction.startSegment("save customer")
   // business logic here
   segment.end()
}

我尝试隔离 newRelic 依赖项,现在可以在我的整个应用程序中重用它:

fun saveCustomer() {
   newRelic.executeWithSegment { // this starts/ends the segment and calls the function block
      // business logic here
   }
}

然而,这使得 saveCustomer 的单元测试变得更加困难,因为在模拟 newRelic.executeWithSegment 之后(我必须这样做;否则在测试中会联系 New Relic),代码块(业务逻辑)是不再执行 - 所以测试失败。

有没有办法满足这些要求? (也许使用注释或使用 Kotlin 委托模式或什至一些轻量级库;不确定。)

您可以使用 AspectJ。

  • 它独立于Spring,比Spring AOP更强大、更高效(无代理)。
  • 它应该适用于任何 JVM 语言,尽管我从未尝试将 Kotlin 作为我方面的目标。
  • 如果您进行编译时织入,AspectJ 运行时是您唯一需要的依赖项。它的大小是120K。
  • 对于加载时织入,您需要 AspectJ 织入代理。它的大小是1.9M。