我尝试了一些似乎可以编译但在单元测试期间抛出 NullPointer 异常的东西,所以我想知道如何才能克服单元测试中的限制。我有一个看起来像这样的类:
class LogWriter extends Actor{
def receive{
case x:Timing => log.info(x toString)
case x:Event => log.info(x toString)
case x:Any => log.warning("Improper message sent to LogWriter, %s".format(x toString))
}
}
但是尝试使用 Specs2 和 Mockito 支持进行单元测试,其中包括:
class LogWriterSpec extends Mokito with Specification{
val mockedLog = mock[Logger]
class MockedLogWriter extends LogWriter{
@transient override val log = mockedLog
}
val writer = actorOf(new MockedLogWriter).start
def testTiming = {
val message = Timing("testTiming", 15 seconds)
writer !! (message, 400)
there was one(mockedLog).info(message toString)
}
def is = "A LogWriter" ^
"should write a Timing message to log.info" ! testTiming ^
end
}
在编译时会产生上述结果NullPointerException
:
[akka:event-driven:dispatcher:global-10] ERROR akka.actor.Actor$ - Problem
java.lang.NullPointerException
at akka.util.Logger.warning_$qmark(Logging.scala:43)
at akka.util.Logger.warning(Logging.scala:117)
我尝试将其更改为使用一些覆盖 AkkaLogging
特征的“日志”对象的 mixin 特征,但编译器不允许这样做。编译器的回复类似于“我们不希望你犯一个无意的错误”。啊! 我想要那个“错误”。
有人知道另一种方式吗?我不拘泥于 Mockito,欢迎任何建议。