I have the following simplified code
class Foo() {
suspend fun bar() {
val headers = AtomicReference(Metadata())
val metadata = headers.get()
if (metadata.keys().size > 0) { // I want it to return a value specified in the test file
// ...
}
}
How can I mock AtomicReference
or Metadata
so that for example headers.get().keys().size
returns a specified value and not the real one?
CodePudding user response:
You can mock the constructor of Metadata
using Constructor Mocks:
mockkConstructor(Metadata::class)
every { anyConstructed<Metadata>().keys() } returns mockedKeys
Note that mockedKeys of keys is your test data.
See https://mockk.io/#constructor-mocks
Additionally, try to architect your code in a fashion that you don't need to mock any constructor (like for example using inversion of control), you will see that it pays dividends when testing.