1
votes

I have a class. It has a companion object A with a factory method.

class A private[somepackage](x: Int) {

}

object A { def createA(y: Int): A = { new A(y) } }

Now I need to create the mock object of A in a scalatest file which is in a different package.

When I give

private val a = mock[A] --> I get compilation error.

constructor A in class A cannot be accessed in <<somewhere>>. Is there a better way to mock the object ??

2
well I hate to be that guy, but if this is code in your own base then it needs some tweaking - not really a workaround I'd recommend exploring. This is a code smell. That being said, you can use reflections to change accessibility of objectsnbpeth

2 Answers

1
votes

In your test sources, create a test double in the same package:

package somepackage

class MockableA extends A(0)

then just create a mock[MockableA] in your tests and continue as usual.

But the answer with a proxy/facade should work too if you are willing to change production sources to facilitate tests.

0
votes

Consider using a proxy to access class A, and stub/mock that proxy class instead. E.g., if A.doStuff is what you want to mock/stub, and A.accessStuff is what you need in your code, create a class

class ADecorated(underlying: A) {
  def doStuff() {
    underlying.doStuff()
    // whatever I want to do
  }

  def accessStuff() {
    x = underlying.accessStuff()
    // do something else and return
  }
 // Any other method you want to use
}

Replace usage of A.createA with new ADecorated(A.createA()). ADecorated is what you work with now