ScalaMock,意外调用 : <mock-1> when sharing mock instance between tests

标签 scala unit-testing testing scalatest scalamock

我正在使用 Scala 2.10ScalaMock 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 {
   ...
}

现在:

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

现在,出于某种原因,当同时运行所有这些测试时,第 4 次测试失败并出现以下错误。如果单独运行,它会通过。

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 声明及其在第 4 个 it should { ... } 测试场景中的行为。然后测试工作(单独地,以及一起)。

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

最佳答案

org.scalatest.OneInstancePerTest 中混合 here :

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

关于ScalaMock,意外调用 : <mock-1> when sharing mock instance between tests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44525865/

相关文章:

scala - 如何在不收集的情况下将RDD,Dataframe或Dataset直接转换为Broadcast变量?

linux - 为 scala.sys.process 进程提供引用参数

python mock_open 断言多个写入调用

Angular 6 ngrx 商店测试 : cannot read ids of undefined

unit-testing - XUnit 是否跨测试类共享 fixture 实例?

java - 使用 XSLT 转换 XML 时出现 ArrayIndexOutOfBoundsException

scala - 如何为 SBT 设置本地代理存储库?

javascript - 如何等到 vscode.windows.terminal 操作结束?

java - 使用数据提供者编写 Java 测试

unit-testing - 在运行完所有测试之后,是否可以执行拆解功能?