我有戏!2 应用程序(Scala),我有一些类在遇到错误时需要执行日志记录。
我希望能够对这些日志记录操作实际发生在正确的条件下进行单元测试。为此,我需要能够模拟记录器,但我遇到了 Mockito 的一些问题。我所拥有的(简化的)看起来像
import play.api.{ Logger, LoggerLike }
trait BaseService {
val log: LoggerLike
def fail(reason: String) {
log.error(reason)
}
}
object Service extends BaseService {
val log = Logger
}
然后在测试中
import org.specs2.mutable._
import org.specs2.mock._
import services.BaseService
object Service extends BaseService with Mockito {
val log = mock[play.api.Logger]
def verify(key: String) = {
there was one(log).error(key)
}
}
class ServiceSpec extends Specification {
"failures should be logged" in {
Service.fail("foo")
Service.verify("foo")
}
}
但我得到了错误
[error] NullPointerException: null (Logger.scala:43)
[error] play.api.LoggerLike$class.isErrorEnabled(Logger.scala:43)
[error] play.api.Logger.isErrorEnabled(Logger.scala:147)
[error] play.api.LoggerLike$class.error(Logger.scala:127)
[error] play.api.Logger.error(Logger.scala:147)
[error] services.BaseService$class.fail(Service.scala:19)
[error] Service$.fail(ServiceSpec.scala:11)
...
我尝试添加
log.isErrorEnabled returns true
log.error(any[String]) returns {}
但随后即使服务的初始化也失败了。