Mockk: staticMockk to Mock Companion Object?

Created on 12 Apr 2018  路  2Comments  路  Source: mockk/mockk

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//kafka readOnlyStore

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

help wanted

Most helpful comment

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.

All 2 comments

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

Was this page helpful?
0 / 5 - 0 ratings