如何使用scalamock模拟具有构造函数参数的类

时间:2017-09-06 23:37:13

标签: scala scalamock

我知道如何模拟没有构造函数参数的类

如, myMock = mock[MockClass]

但是,如果类有构造函数参数,你会怎么做?

更具体地说,我试图嘲笑finatra类:ResponseBuilder

https://github.com/ImLiar/finatra/blob/master/src/main/scala/com/twitter/finatra/ResponseBuilder.scala

1 个答案:

答案 0 :(得分:2)

我在github上找不到测试类但是这个问题的答案取决于你想要实现的目标。你不会嘲笑一个类,但使用specs2mockito可以监视它,以确定是否发生了某些事情,这是你可能想要实现的一个例子。

class Responsebuilder(param1: Int, param2: int) {
    def doSomething() { doSomethingElse() }
    def doSomethingElse() { ...
}

class ResponseBuilderSpec extends Specification with Mockito {
    "response builder" should {
        "respond" in {
            val testClass = spy(new ResponseBuilder(1, 3))
            testClass.doSomething()

            there was one(testClass).doSomethingElse()
        }
    }
}

通常会将特征模拟为依赖关系,然后在定义其行为后将其注入测试类

trait ResponseBuilderConfig { def configurationValue: String }

class Responsebuilder(val config: ResponseBuilderConfig, param2: int) {
    def doSomething() { doSomethingElse(config.configurationValue) }
    def doSomethingElse(param: String) { ...
}

class ResponseBuilderSpec extends Specification with Mockito {
    "response builder" should {
        "respond" in {
            val mockConfig = mock[ResponseBuilderConfig]
            mockConfig.configurationValue returns "Test"
            val testClass = spy(new ResponseBuilder(mockConfig, 3))
            testClass.doSomething()

            there was one(testClass).doSomethingElse("Test")
        }
    }
}