我有戏!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 {}
但是随后甚至服务的初始化也失败了。
我不是Mockito专家,但我认为您的mock在这里出现了故障,因为堆栈跟踪显示了被调用的实际播放Logger
方法。这可能是因为您试图在这里模拟Scala object
。如果你嘲笑这样的特性
val log = mock[play.api.LoggerLike]
你会越过这个特定的错误,进入下一个问题——你的验证不起作用:
[error] The mock was not called as expected:
[error] Argument(s) are different! Wanted:
[error] loggerLike.error(
[error] ($anonfun$apply$mcV$sp$1) <function0>
[error] );
[error] -> at Service$$anonfun$verify$1.apply$mcV$sp(ServiceSpec.scala:10)
[error] Actual invocation has different arguments:
[error] loggerLike.error(
[error] ($anonfun$fail$1) <function0>
[error] );
[error] -> at services.BaseService$class.fail(x.scala:57)
[error] (ServiceSpec.scala:17)
这是由于日志消息是按名称参数(因此是匿名函数)而不是字符串传递的,请参阅此问题以进行进一步讨论。