How do you use scalamock to mock a class with constructor parameters

7.1k views Asked by At

I know how to mock a class that has no constructor parameters

e.g., myMock = mock[MockClass]

However, what do you do if the class has constructor parameters?

More specifically I'm trying to mock the finatra class: ResponseBuilder

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

1

There are 1 answers

0
ChocPanda On BEST ANSWER

I couldn't find the test class on github however the answer to this depends on what you want to achieve. You wouldn't mock a class however using specs2 and mockito you can spy on it to determine if something has happened this is an example of what you might be trying to achieve.

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

One would normally mock traits as dependencies and then inject them into the test class once you defined their behaviour

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