29

Can somebody tell me how should I unit-test extension functions in Kotlin? Since they are resolved statically should they be tested as static method calls or as non static ? Also since language is fully interoperable with Java, how Java unit test for Kotlin extension functions should be performed ?

TheTechWolf
  • 2,084
  • 2
  • 19
  • 24

1 Answers1

29

Well, to test a method, whether static or not, you call it as real code would do, and you check that it does the right thing.

Assuming this extension method, for example, is defined in the file com/foo/Bar.kt:

fun String.lengthPlus1(): Int {
    return this.length + 1
}

If you write your test in Kotlin (which you would typically do to test Kotlin code), you would write

assertThat("foo".lengthPlus1()).isEqualTo(4);

If you write it in Java (but why would you do that?)

assertThat(BarKt.lengthPlus1("foo")).isEqualTo(4);
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 1
    Never intended to write Java tests for Kotlin that would be really bad idea :) It was more to check how it behaves that way. But what about if I want to verify if that method is called (using Mockito for example) and not to check return value? – TheTechWolf Feb 21 '17 at 23:04
  • As the Java code shows, an extension method is actually a static method. Mockito can't mock static methods. – JB Nizet Feb 21 '17 at 23:05
  • 3
    @TheTechWolf you really shouldn't be concerned with checking whether or not your extension method was called, you should just verify that the expected result is there. If your extension method is overly complex and requires asserting its invocation, it probably should be refactored out into a more testable class. Though this all depends on your use case and what the extension function is actually doing, what's your use case? – Mitch Ware Sep 11 '17 at 15:02
  • I agree with @MitchWare. Extensions functions should be really simple. If it feels like you need to write tests for it, just extract it as a class, mock it where needed and write test for it. – rontho Jan 11 '18 at 08:55
  • 3
    what if those extensions are inside a class? – Luís Soares Apr 08 '18 at 10:29
  • 9
    Exactly - how can I test an extension function that is defined within a class? That's the search that brought me to this question - which is not answered at all here. Sad. Testing a top-level extension function is easy and not even worth the question and answer... – Zordid Nov 18 '20 at 14:16
  • I got a Unresolved reference error – truongnm Feb 14 '23 at 12:02