ScalaMock. Mock a class that takes arguments

女生的网名这么多〃 提交于 2019-11-30 20:31:18

The insight is that what you need to mock is socketClientFactory. And then set it up to return a mock SocketClient.

Given:

trait SocketClient {
  def frobnicate(): Unit
}

class ScannerBase(path: String)

class XScanner[T <: SocketClient](
  confPath: String = "/etc/default/configPath",
  socketClientFactory: String => T
) extends ScannerBase(confPath) {
  val socket = socketClientFactory("Some Socket Name")
  socket.frobnicate
}

(side note - your default value for confPath can never be used because there's no default value for socketClientFactory).

then this should get you started (this is with Scala 2.9.x and ScalaMock2 - 2.10.x with ScalaMock3 will be slightly different, but not much so):

import org.scalatest.FunSuite
import org.scalamock.scalatest.MockFactory
import org.scalamock.generated.GeneratedMockFactory

class ScannerTest extends FunSuite with MockFactory with GeneratedMockFactory {

  test("scanner") {
    val mockFactory = mockFunction[String, SocketClient]
    val mockClient = mock[SocketClient]
    mockFactory.expects("Some Socket Name").returning(mockClient)
    mockClient.expects.frobnicate
    val scanner = new XScanner("path/to/config", mockFactory)
  }
}

For completeness, here's the same test in Scala 2.10.0 and ScalaMock3:

import org.scalatest.FunSuite
import org.scalamock.scalatest.MockFactory

class ScannerTest extends FunSuite with MockFactory {

  test("scanner") {
    val mockFactory = mockFunction[String, SocketClient]
    val mockClient = mock[SocketClient]
    mockFactory.expects("Some Socket Name").returning(mockClient)
    (mockClient.frobnicate _).expects()
    val scanner = new XScanner("path/to/config", mockFactory)
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!