How should I test Kotlin extension functions?

11,531

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);
Share:
11,531

Related videos on Youtube

TheTechWolf
Author by

TheTechWolf

Updated on June 13, 2022

Comments

  • TheTechWolf
    TheTechWolf about 2 years

    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
    TheTechWolf over 7 years
    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?
  • JB Nizet
    JB Nizet over 7 years
    As the Java code shows, an extension method is actually a static method. Mockito can't mock static methods.
  • Mitch Ware
    Mitch Ware almost 7 years
    @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?
  • rontho
    rontho over 6 years
    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.
  • Luís Soares
    Luís Soares about 6 years
    what if those extensions are inside a class?
  • Zordid
    Zordid over 3 years
    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...