Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I test Kotlin extension functions?

Tags:

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 ?

like image 871
TheTechWolf Avatar asked Feb 21 '17 22:02

TheTechWolf


People also ask

How do you think extension functions in Kotlin are useful?

Extension functions are a cool Kotlin feature that help you develop Android apps. They provide the ability to add new functionality to classes without having to inherit from them or to use design patterns like Decorator. Read more about Decorator pattern on Wikipedia.

How do you access the extension function in Kotlin?

In Kotlin, you can easily call another function by just importing the same in the current Kotlin file where your main function is running. Whatever the function we are declaring in a Kotlin file will be compiled into a static method by default, and it will be placed under the same package.

Are Kotlin extension functions static?

Kotlin with top-level extension function is a pure Java class with a static method. That's why it needs to somehow pass the original String.


1 Answers

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); 
like image 120
JB Nizet Avatar answered Sep 19 '22 23:09

JB Nizet