如何使用Scalamock用构造函数参数模拟类



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

,例如, myMock = mock[MockClass]

但是,如果类具有构造函数参数,该怎么办?

更具体地说,我正在尝试模拟Finatra类:ResponseBuilder

https://github.com/imliar/finatra/finatra/blob/master/src/main/scala/com/com/twitter/finatra/finatra/responsebuilder.scala

我在github上找不到测试类,但是答案取决于您想要实现的目标。您不会使用Specs2和Mockito模拟一堂课,您可以在上面监视它以确定是否发生了什么事,这是您可能要实现的示例。

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

相关内容

  • 没有找到相关文章

最新更新