首页 > 解决方案 > 如何在 Kotlin 中进行方法检测 - 但保持方法可测试

问题描述

我有一个方法需要检测来调用 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 委托模式,甚至是一些轻量级库;不确定。)

标签: kotlinaopnewrelic

解决方案


您可以使用 AspectJ。

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

推荐阅读