Reputation: 474
I've the following trait which I want to mock:
trait TraitA extends TraitB {
private lazy val internalObject = new ServiceA()
internalObject.setSomeVal("someVal")
internalObject.setSomeOtherval("someOtherVal")
private lazy val anotherObject = new ServiceB()
def functionA(paramA: typeB): typeC = {
// some code using internalObject & anotherObject
}
}
When using ScalaMock, I try to do
val mockTraitA = mock[TraitA]
it fails with java.lang.NullPointerException
as probably it is not able to initialize the mock version of this trait properly due to the presence of private lazy val's ?
What could be the correct way to initialize such a trait?
Upvotes: 1
Views: 1045
Reputation: 967
For mockTraitA
, the line internalObject.setSomeVal...
will be executed when the constructor for the trait runs. There's no way to prevent that unfortunately.
If you can, try to refactor to this:
private lazy val internalObject = {
val t = new ServiceA
t.setSomeVal("someVal")
t.setSomeOtherval("someOtherVal")
t
}
Upvotes: 1