【问题标题】:Reuse mock declaration across tests跨测试重用模拟声明
【发布时间】:2016-06-30 21:19:06
【问题描述】:

我想在测试中重复使用模拟声明(如果可能的话)。 这是一个使用 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
  }
}

【问题讨论】:

    标签: scala scalatest


    【解决方案1】:

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

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

    测试类会变成:

    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
      }
    }
    

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

    【讨论】:

      猜你喜欢
      • 2021-08-27
      • 2018-12-17
      • 1970-01-01
      • 2011-12-06
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 2018-05-08
      相关资源
      最近更新 更多