4

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

ThinkBonobo
  • 15,487
  • 9
  • 65
  • 80
  • 1
    (1) `ResponseBuilder` does NOT take constructor parameters. (2) if it did, you could still mock it as `mock[ResponseBuilder]`, the constructor parameters do not matter, (3) it is almost never a good idea to mock builders – Dima Sep 06 '17 at 23:59
  • Mocking classes with non-default constructors (so, with parameters) is actually supported by ScalaMock, in the latest version. – Philipp Sep 08 '17 at 07:53

1 Answers1

3

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")
        }
    }
}
ChocPanda
  • 88
  • 6