gpt4 book ai didi

scala - 使用 Mockito 对 LazyLogging 进行单元测试

转载 作者:行者123 更新时间:2023-12-01 21:54:49 28 4
gpt4 key购买 nike

我有一个扩展 LazyLogging 特性的类

class TaskProcessor()
extends Processor
with LazyLogging {

def a1() = {
logger.info("Test logging")
}
}

现在,我想测试我的日志记录是否有效。所以我按照这个例子Unit test logger messages using specs2 + scalalogging并按如下方式编写了我的测试

 "TaskProcessor" should "test logging" in {

val mockLogger = mock[Logger]
val testable = new TaskProcessor {
override val logger: Logger = mockLogger
}
verify(mockLogger).info("Test logging")
}

出现以下错误

Error:(32, 20) overriding lazy value logger in trait LazyLogging of type com.typesafe.scalalogging.Logger;
value logger must be declared lazy to override a concrete lazy value
override val logger: Logger = mockLogger

为了解决这个问题,我修改了语句

  override val logger: Logger = mockLogger

  override lazy val logger: Logger = mockLogger

出现以下错误

Cannot mock/spy class com.typesafe.scalalogging.Logger
Mockito cannot mock/spy following:
- final classes
- anonymous classes
- primitive types
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class com.typesafe.scalalogging.Logger
Mockito cannot mock/spy following:
- final classes
- anonymous classes
- primitive types
at org.scalatest.mockito.MockitoSugar.mock(MockitoSugar.scala:73)
at org.scalatest.mockito.MockitoSugar.mock$(MockitoSugar.scala:72)

我的依赖如下

 "org.scalatest" %% "scalatest" % "3.0.5" % "test",
"org.mockito" % "mockito-all" % "1.10.19" % Test,
"com.typesafe.scala-logging" %% "scala-logging" % "3.9.2",

谁能指导我如何模拟记录器并进行测试。

最佳答案

问题是 com.typesafe.scalalogging.Logger 类不能被模拟,因为它是最终的,但我们仍然可以模拟底层 org.slf4j.Logger

import org.scalatest.mockito.MockitoSugar
import org.slf4j.{Logger => UnderlyingLogger}
import com.typesafe.scalalogging.Logger
import org.scalatest.{Matchers, WordSpec, FlatSpec}
import org.mockito.Mockito._

class TaskProcessorSpec extends FlatSpec with Matchers with MockitoSugar {

"TaskProcessor" should "test logging" in {

val mockLogger = mock[UnderlyingLogger]
when(mockLogger.isInfoEnabled).thenReturn(true)

val testable = new TaskProcessor {
override lazy val logger = Logger(mockLogger)
}
testable.a1()

verify(mockLogger).info("Test logging")
}
}

关于scala - 使用 Mockito 对 LazyLogging 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58564149/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com