我需要一些关于如何使用 ScalaMock 在类中模拟高阶函数的帮助
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}
class TestSpec extends FlatSpec with MockFactory with Matchers {
class Foo {
def foo(f: () ⇒ String) = "this is foo"
}
val fooMock = mock[Foo]
"Failing test" should "pass but doesn't" in {
(fooMock
.foo(_: () ⇒ String))
.expects({ () ⇒
"bar"
})
.returns("this is the test")
// will fail here
val result = fooMock.foo({ () ⇒
"bar"
})
assert(true)
}
"Passing test" should "that passes but I can't do it this way" in {
val f = { () ⇒
"bar"
}
(fooMock.foo(_: () ⇒ String)).expects(f).returns("this is the test")
val result = fooMock.foo(f)
result shouldBe "this is the test"
}
}
正如您在上面的代码中看到的那样,当您传入一个具有更高阶函数的值时,被模拟的函数可以正常工作,但如果您在每个位置都输入它,则不会。在我的用例中,我不能像在第二次测试中那样做
以下是有关用例的更多信息,但并非完全有必要回答这个问题
这是一个简化的示例,但我需要一种方法来让前者工作。原因是(我会尽力解释这一点)我有一个正在测试的 A 类。A 内部是一个传递模拟类 B 的函数,基本上 foo 函数(如下所示)在这个模拟 B 内部,我不能像在下面的第二个示例中那样只传递 f。如果这没有任何意义,我可以尝试准确地复制它。
TL;DR 我需要第一次测试才能工作,哈哈
任何想法为什么会发生这种情况?
如果您对我为什么需要这样做感到好奇,这里有一个更准确的示例,说明我是如何使用它的:
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}
class TestSpec extends FlatSpec with MockFactory with Matchers {
class Foo {
def foo(f: () ⇒ String) = s"you sent in: ${f()}"
}
object Bar {
def bar(foo: Foo): String = {
val f = { () ⇒ "bar" }
foo.foo(f)
}
}
val fooMock = mock[Foo]
"Failing test" should "pass but doesn't" in {
(fooMock.foo(_: () ⇒ String))
.expects({ () ⇒
"bar"
})
.returns("this is the test")
// will fail here
val result = Bar.bar(fooMock)
assert(true)
}
}