0

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.

Ken White
  • 123,280
  • 14
  • 225
  • 444
LeYAUable
  • 1,613
  • 2
  • 15
  • 30
  • Is `A.extension()` used anywhere other than class B itself? – João Dias Nov 09 '21 at 18:44
  • Yes, it is there really just for organization purposes because B is a repository class and A.extension() is basically syntatic sugar to for a database operation on instances of A. – LeYAUable Nov 09 '21 at 20:50
  • Then why add such an extension in class B? If there are other classes calling it, why not add it to class A for example? – João Dias Nov 10 '21 at 20:37

1 Answers1

-1

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

ekibet
  • 176
  • 2
  • 8
  • I also had no success. Ended up moving the functions out of the companion object into a regular object/file. – LeYAUable Jan 27 '22 at 15:03
  • How about in the case where the function in main activity needs to be statically defined. How can i go about it – ekibet Jan 30 '22 at 04:38
  • I don't know much about android development since I use Kotlin for micro-service development. That being said, you can either place the function in a regular object instead of a companion object, and that makes it mockable. Or, if outside any formally defined scope, like outside the "class/activity" brackets, which also makes it static. Both ways make it mockable via mockStatic. – LeYAUable Jan 30 '22 at 18:35