我尝试了一些似乎可以编译但在单元测试期间抛出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)
我试着改变它,使用一些mixin trait覆盖了Akka Logging
trait的"日志"对象,但编译器不允许它。编译器的回答类似于"我们不希望您犯一个无意的错误"。啊!我想要那个错误。"
谁知道另一种方法?我不是一定要用Mockito,欢迎大家的建议
Scalamock是一个本地Scala模拟框架(在其他框架中,它允许模拟函数)。您可以在这里找到完整的示例:
http://www.paulbutcher.com/2011/11/scalamock-step-by-step/也许它能解决你的问题。