Search code examples
kotlinkotlin-extension

Testing Kotlin extensions inside a class


I know it's possible to test global extensions, but how to test Kotlin extensions inside a class?

class D

class C {
  fun D.foo() {
    println("123")
  }
}

Should I interpret D.foo as private of D or can it be unit tested?


Solution

  • Use either with, apply or run (or any other method that supplies the enclosing C instance) to access the foo method of D.

    The reason why you can't access it directly is that D.foo is only accessible from an instance of type C.

    Sample:

    val c = C()
    c.run { // apply or with
      D().foo() // accessible
    }
    
    D().foo() // not accessible
    

    The following works too, but usage is not so nice:

    D().run {
      C().run {
        foo() // accessible
      }
    }
    

    Funny thing: this discussion mentions that support for multiple receivers is in the backlog, but any further discussions just say that multiple receivers are not supported and there are no plans to support it. Maybe there is support in future and then the method to call it may become easier.