Reputation: 695
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 ??
Upvotes: 1
Views: 519
Reputation: 967
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.
Upvotes: 1
Reputation: 1392
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
Upvotes: 0