3

我正在Scala 2.10使用ScalaMock 3.6.

我有一个非常简单的测试用例,有 4 个测试场景。我mock为这些测试创建了一个对象(模仿文件系统):

class ProcessingOperatorTest extends FlatSpec with Matchers with BeforeAndAfterEach with MockFactory {
...

val fakeFS = mock[FileIO]
(fakeFS.createFile _).expects(*).returns(true).anyNumberOfTimes()
(fakeFS.exist _).expects(where { (p: String) => p.contains(existing) }).returns(true).anyNumberOfTimes()
(fakeFS.exist _).expects(where { (p: String) => p.contains(notExisting) }).returns(false).anyNumberOfTimes()

behavior of "Something"
it should "test 1" in {
   ...
}

it should "test 2" in {
   ...
}

it should "test 3" in {
   ...
}

it should "test 4" in {
   ...
}

现在:

  • 第一个测试不使用任何模拟方法(但需要模拟对象)
  • 第二次测试仅使用existing模拟方法
  • 第三次测试同时使用existingnot existing模拟方法
  • 第四次测试使用所有方法,(也createFile

现在,由于某种原因,当一起运行所有这些测试时,第四次测试失败给我以下错误。如果单独运行,它将通过。

Unexpected call: <mock-1> FileIO.exist(notExisting)

Expected:
inAnyOrder {

}

Actual:
  <mock-1> FileIO.exist(notExisting)
ScalaTestFailureLocation: scala.Option at (Option.scala:120)
org.scalatest.exceptions.TestFailedException: Unexpected call: <mock-1> FileIO.exist(notExisting)

...

另一个解决方法是在第四个测试场景中复制粘贴mock声明及其行为。it should { ... }然后测试工作(单独和一起)。

为什么全局mock实例失败?如果需要,我可以尝试准备一个类似的测试场景作为单独的sbt项目。

4

1 回答 1

7

org.scalatest.OneInstancePerTest按照此处所述混合:

class ProcessingOperatorTest extends FlatSpec
                             with Matchers
                             with BeforeAndAfterEach
                             with MockFactory
                             with OneInstancePerTest {
  ...
}
于 2017-06-13T15:53:50.307 回答