2

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?

Luís Soares
  • 5,726
  • 4
  • 39
  • 66
  • Possible duplicate of [Testing extension functions inside classes](https://stackoverflow.com/questions/50702478/testing-extension-functions-inside-classes) – JavierSA Jul 26 '18 at 19:32

2 Answers2

4

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.

Roland
  • 22,259
  • 4
  • 57
  • 84
  • downvoting answers or questions without any comment why, is not really helpful. If the answer is wrong, then it may make sense and should be mentioned. – Roland Aug 02 '18 at 14:19
3

The foo function is a public method on C, but since a method call can't have two receivers, you have to use the with function. Like this:

with(C()) {
    D().foo()
}
marstran
  • 26,413
  • 5
  • 61
  • 67