Hello,
Can I use staticMockk function to mock a companion object?
I got something like
class StreamingStore private constructor() {
companion object {
private val store: ReadOnlyKeyValueStore
get(key:UUID): DomainObject{
val message = store.get(key.toString())
//logic
return DomainObject
}
}
On my test I tried
staticMockk("package.StreamingStore").use {
every {
get(uuid.toString())
} returns DomainObject(UUID.randomUUID())
}
but it's not working
Companions are in reality appended by ".Companion" i.e. "package.StreamingStore.Companion"
So to fix your construct:
staticMockk<StreamingStore.Companion>().use {
every {
get(uuid.toString())
} returns DomainObject(UUID.randomUUID())
}
but I doubt you need staticMockk. Try following:
objectMockk(StreamingStore.Companion).use {
every {
get(uuid.toString())
} returns DomainObject(UUID.randomUUID())
}
objectMockk is designed to work with objects and compnaions are not static till the moment you put @JvmStatic annotation.
Thank you, It worked with a variation on the examples, but I think I missed that the purpose is to be able to use this mock without injecting or passing to the Tested class. Maybe something like PowerMock can help, unfortunately I'm using JDK 9 and it its incompatible.
Many Thanks for your help
Most helpful comment
Companions are in reality appended by ".Companion" i.e. "package.StreamingStore.Companion"
So to fix your construct:
but I doubt you need staticMockk. Try following:
objectMockk is designed to work with objects and compnaions are not static till the moment you put
@JvmStaticannotation.