Scala 对象的 Mockito
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16443801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mockito for Objects in Scala
提问by Marius Stroe
I'm using Scala 2.10, specs2 and Mockito. I want to mock scala.io.Source.fromURL(). The issue seems to be fromURL() is a function in io.Source's object.
我正在使用 Scala 2.10、specs2 和 Mockito。我想模拟 scala.io.Source.fromURL()。问题似乎是 fromURL() 是io.Source's object 中的一个函数。
val m = mock[io.Source]
m.fromURL returns io.Source.fromString("Some random string.")
It's a pretty straightforward mock in an Unit test. Why isn't it working?
这是单元测试中非常简单的模拟。为什么它不起作用?
Thanks!
谢谢!
回答by cmbaxter
Instead of mocking it, you could try spyingit as follows:
您可以spying按如下方式尝试,而不是嘲笑它:
val m = spy(io.Source)
Or you could mock it as follows:
或者你可以模拟它如下:
val m = mock[io.Source.type]
But then how are you using Sourcein the class you are testing? If you had an example class like so:
但是,您Source在正在测试的课程中的使用情况如何?如果您有这样的示例类:
class MyClass{
def foo = {
io.Source.doSomething //I know doSomething is not on Source, call not important
}
}
Then in order to take advantage of mocking/spying, you'd have to structure your class like so:
然后为了利用模拟/间谍,你必须像这样构建你的类:
class MyClass{
val source = io.Source
def foo = {
source.doSomething
}
}
And then your test would have to look something like this:
然后你的测试必须看起来像这样:
val mockSource = mock[io.Source.type]
val toTest = new MyClass{
override val source = mockSource
}
In the Java world, static methods are the bane of mocking. In the Scala world, calls to objects can also be troublesome to deal with for unit tests. But if you follow the code above, you should be able to properly mock out an object based dependency in your class.
在 Java 世界中,静态方法是模拟的祸根。在 Scala 世界中,对对象的调用对于单元测试来说处理起来也很麻烦。但是如果你遵循上面的代码,你应该能够在你的类中正确地模拟出基于对象的依赖项。

