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 ?
How should I test Kotlin extension functions?
Asked Answered
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);
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? –
Fennessy
As the Java code shows, an extension method is actually a static method. Mockito can't mock static methods. –
Armandoarmature
@Fennessy 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? –
Eyeopening
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. –
Savaii
what if those extensions are inside a class? –
Disjoint
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... –
Trumpeter
I got a Unresolved reference error –
Sivia
© 2022 - 2024 — McMap. All rights reserved.