Scala中对象的Mockito [英] Mockito for Objects in Scala

查看:243
本文介绍了Scala中对象的Mockito的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Scala 2.10,specs2和Mockito.我想模拟scala.io.Source.fromURL().问题似乎是fromURL()是 io.Source的对象中的一个函数.

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.

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?

谢谢!

推荐答案

除了模拟它,您还可以尝试spying,如下所示:

Instead of mocking it, you could try spying it as follows:

val m = spy(io.Source)

或者您可以如下模拟它:

Or you could mock it as follows:

val m = mock[io.Source.type]

但是您如何在要测试的类中使用Source?如果您有这样的示例类:

But then how are you using Source in the class you are testing? If you had an example class like so:

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
}

在Java世界中,静态方法是嘲讽的祸根.在Scala世界中,对对象的调用在进行单元测试时也很麻烦.但是,如果您遵循上面的代码,则应该能够在类中正确模拟出基于对象的依赖关系.

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.

这篇关于Scala中对象的Mockito的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆