0

I am trying to mock a class which takes some ctor parameters and does some work in the constructor.

Other than wrapping the naughty class I am trying to mock, is there anything in ScalaMock that will actually avoid calling the constructor (as its currently throwing a NPE in the construct method)

Cheetah
  • 13,785
  • 31
  • 106
  • 190

1 Answers1

0

No that is not possible. All mocks are subclasses of the type to mock, so the constructor will always be called. You could however construct mocks for the types used in the constructor and specify a concrete subtype. E.g.

import ConstructorWorkaroundTest.{HardToMock, Something}
import org.scalamock.scalatest.MockFactory
import org.scalatest.FunSuite

class ConstructorWorkaroundTest extends FunSuite with MockFactory {
  test("does not work") {
    val m = mock[HardToMock]
  }

  test("works") {
    val s = stub[Something]
    class BetterToMock extends HardToMock(s)
    val m = mock[BetterToMock]

    m.foo _ expects() returning "hello" once()
    m.foo()
  }
}

object ConstructorWorkaroundTest {
  trait Something { def length: Int }

  class HardToMock(s: Something) {
    val naughty = s.length
    def foo() = "hi"
  }
}
Philipp
  • 967
  • 6
  • 16