【问题标题】:How to inject log property in Grails 3 unit tests?如何在 Grails 3 单元测试中注入日志属性?
【发布时间】:2015-12-03 18:46:24
【问题描述】:

我正在尝试将我的 Grails 2 项目升级到 Grails 3。我在为使用日志记录的代码块运行测试时遇到问题,因为它会为 log 属性抛出 NoSuchPropertyException。这在 Grails 2 中没有问题,因为属性是自动注入的。我如何让它在 Grails 3 中工作?我正在使用 3.0.2。

【问题讨论】:

  • 你有一个类,其中有log.... 调用,用@Slf4j 注释,它在你的应用程序中都可以工作,但是在你的测试中从该类调用代码时它会失败?
  • log 据说是由框架自动注入的。 Grails 2 中不需要注释,甚至不需要声明。

标签: unit-testing grails grails-3.0


【解决方案1】:

@groovy.util.logging.Slf4j 类注解添加到您的规范中,log 将被注入。

【讨论】:

    【解决方案2】:

    我一直在我的 Groovy 课程中这样做,我不知道这是否适用于您的测试:

    import org.slf4j.Logger
    import org.slf4j.LoggerFactory
    
    // within my class that I want to call log on
    private static final Logger log = LoggerFactory.getLogger(MyClass.class)
    
    // now you can call log from within a method
    log.info("Log foo") 
    

    【讨论】:

    • 我认为这不是@PsychoPunch 正在寻找的答案。每个 Grails 工件(控制器、服务、标记库、..)都会获得由 Grails 2 框架注入的 log 实例。在 Grails 3.0 中是否发生了变化?
    • 我发现log 实例没有自动注入到 Grails 3 中,它在 2.4.3 版本中就已经存在。我在回答中引用的解决方法是我如何完成它。
    猜你喜欢
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多