8

我正在使用 scalamock 来模拟一个包含一些重载方法的类,但我遇到了一些错误。

例如:

val out = mock[PrintStream]

(out.print _).expects("cmd \r\n")

引发以下错误:

[error] [...]/src/test/scala/chili.scala:19: ambiguous reference to overloaded definition,
[error] both method print in class PrintStream of type (x$1: String)Unit
[error] and  method print in class PrintStream of type (x$1: Array[Char])Unit

但如果我尝试使用:

(out.print(_: String)).expects("cmd \r\n")

我也收到一个错误:

[info] [...]/src/test/scala/chili.scala:19: Unable to resolve overloaded method print
[info]       (out.print(_: String)).expects("cmd \r\n")
[info]                 ^
[error] [...]/src/test/scala/chili.scala:19: value expects is not a member of String => Unit
[error]       (out.print(_: String)).expects("cmd \r\n")

有没有办法在scala中做到这一点?也许使用另一个库?

4

1 回答 1

16

我相信您看到的编译器错误与 scalamock 无法正确模拟PrintStream该类有关。如果查看 scalamock scaladocs,您将看到以下语句:

At present, ScalaMock can only mock traits, Java interfaces, and non-final 
classes that define a default constructor

由于PrintStream该类既不是接口也没有默认构造函数,我的猜测是 scalamock 无法正确模拟它,而您看到的错误是它的副作用。如果您将代码更改为使用 a OutputStream(这是一个接口,因此符合 scalamock 的限制),您可以像这样进行重载方法模拟:

val mockStream = mock[OutputStream]      
(mockStream.write(_:Int)) expects(1)
(mockStream.write(_:Array[Byte])) expects(Array[Byte](1,2,3))

就个人而言,我更喜欢在 Specs2 中使用Mockito,因为它没有这些限制。PrintWriter使用 Mockito 模拟的类的示例,然后是该类的测试规范,如下所示:

import java.io.PrintStream
import java.io.File
import org.specs2.mutable.Specification
import org.specs2.mock.Mockito

class MockitoExample extends Specification with Mockito{
  val mockPrinter = mock[PrintStream]
  val myPrinter = new MyPrintingClass{
    override val printer = mockPrinter
  }

  "A request to print and attay of strings" should{
    "call println on the PrintStream for each string supplied" in {
      myPrinter print Array("foo", "bar")
      there was one(mockPrinter).println("foo")
      there was one(mockPrinter).println("bar")
    }
  }
}

class MyPrintingClass{
  val printer = new PrintStream(new File("foo.txt"))

  def print(strings:Array[String]) = strings foreach (printer.println(_))
}

现在这是一个非常简单的例子,只使用没有测试前桩的测试后验证(因为println有一个Unit返回类型),但至少你可以看到 Mockito 没有受到与 scalamock 相同的限制。您可以在此处阅读有关将 Mockito 与 Specs2 一起使用的更多信息。

于 2013-06-03T12:43:15.070 回答