跨测试重用模拟声明

Reuse mock declaration across tests

我想在测试中重用模拟声明(如果可能)。 这是一个使用 ScalaTest 和 Mockito 的最小非工作示例。我期待第一次测试中的 yes 值,但我得到了 other 值。

似乎最新的Mockito.when是所有测试条款都申请的

有没有办法避免在每个 in 子句中声明模拟?

import org.mockito.Mockito._
import org.scalatest.mock.MockitoSugar
import org.scalatest.{Matchers, WordSpec}
​
class ReuseMocksSpec extends WordSpec with Matchers with MockitoSugar {

  "A test" when {
    val service = mock[Service]
    "sharing mocks among tests" should {
      when(service.getVal).thenReturn("yes")
      "get yes value" in {
        service.getVal should be("yes")
      }
    }
    "sharing mocks among other tests" should {
      when(service.getVal).thenReturn("other")
      "get other value" in {
        service.getVal should be("other")
      }
    }
  }
​
  trait Service {
    def getVal: String
  }
}

我回顾了我的设计方式,现在正在使用一个函数来构建我的模拟:

def withValue(value: String)(body: (Service => String)) = {
  val service = mock[Service]
  when(service.getVal).thenReturn(value)
  body(service)
}

测试 class 将变为:

import org.mockito.Mockito._
import org.scalatest.mock.MockitoSugar
import org.scalatest.{Matchers, WordSpec}

class ReuseMocksSpec extends WordSpec with Matchers with MockitoSugar {

  "A test" when {
    "sharing mocks among tests" should {
      "get yes value" in {
        val value = withValue("yes") { service =>
          service.getVal
        }
        value should be("yes")
      }
    }
    "sharing mocks among other tests" should {
      "get other value" in {
        val value = withValue("other") { service =>
          service.getVal
        }
        value should be("other")
      }
    }
  }

  def withValue(value: String)(body: (Service => String)) = {
    val service = mock[Service]
    when(service.getVal).thenReturn(value)
    body(service)
  }

  trait Service {
    def getVal: String
  }
}

我不知道这是否是最干净、最简单的方法,但它确实有效...