【问题标题】:ScalaTest : inject implicit variableScalaTest:注入隐式变量
【发布时间】:2019-12-01 00:52:54
【问题描述】:

我来自 Java 背景,我正在尝试使用 Scala 编写单元测试。

我的班级如下:

import com.softwaremill.sttp.{HttpURLConnectionBackend, Uri, sttp}

class MyClient(endpoint: String, principal: String) {

  private implicit val serialization = org.json4s.native.Serialization
  private implicit val backend = HttpURLConnectionBackend()

  def getDataSet(id: String) : Option[DataSet] = {
      //sttp.get(url).send <-- will use 'bakend'
  }
}

这里使用隐式变量“backend”来插入 HTTP 客户端实现。

在 UnitTest 中,我应该插入 SttpBackendStub

implicit val testingBackend = SttpBackendStub.synchronous
        .whenRequestMatches(_.uri.path.startsWith("/dataSet"))
        .thenRespond(dataSetJson)

val client = new MyClient("http://dummy", "dummy")

但是当我启动 MyClient 实例时,它仍然会使用 HttpURLConnectionBackend 而不是 SttpBackendStub

是否有在测试期间将“testingBackend”引入 MyClient 的解决方法?

【问题讨论】:

    标签: scala scalatest implicit


    【解决方案1】:

    这里使用隐式会让您认为问题比实际情况更复杂。您将直接在MyClient 中实例化HttpURLConnectionBackend,这就是您将获得的“后端”。如果您想使用不同的,您必须将它传递给 MyClient。你可以给它一个默认值以供生产使用,但在你的测试中实例化它时传入一个模拟。

    class MyClient(endpoint: String, principal: String,
        implicit val backend: BackendInterface = HttpURLConnectionBackend) {
    
      private implicit val serialization = org.json4s.native.Serialization
    
      def getDataSet(id: String) : Option[DataSet] = {
          //sttp.get(url).send <-- will use 'bakend'
      }
    }
    

    在你的测试中:

    val testingBackend = SttpBackendStub.synchronous
            .whenRequestMatches(_.uri.path.startsWith("/dataSet"))
            .thenRespond(dataSetJson)
    
    val client = new MyClient("http://dummy", "dummy", testingBackend)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-02
      • 1970-01-01
      • 2015-03-24
      相关资源
      最近更新 更多