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

查看:30
本文介绍了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)

或者你可以模拟如下:

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天全站免登陆