Mock extensions function inside Companion Object

575 Views Asked by At

I have a class (class A) to which I define an extension function (A.extension()) inside a companion object of another class (class B) for a matter of organization.

On my tests I need:

  • To use a real class A instance .
  • To mock A.extension().
  • To use a mock instance of class B.

Using MockK-library I am not being able to mock that extension function successfully. I've tried:

        mockkObject(B.Companion) {
            every { any<A>().extension() } returns whatIneed
        }

result: Tries to run the unmocked version of the extension function.

        mockkStatic(path.to.B.CompanionKt)
            every { any<A>().extension() } returns whatIneed
   

Result: It does not find the Companion Object.

        mockkStatic(A::extension) {
            every { any<A>().extension() } returns whatIneed
        }

Result: Compile error -> 'extension' is a member and an extension at the same time. References to such elements are not allowed.

Am I missing something regarding how to mock this ? Am I doing something wrong in terms of code structuring that prevents this mocking to be possible?

Any help is appreciated.

1

There are 1 best solutions below

3
ekibet On

This seems to be an impossible thing. I have tried this severally and it does not work.