How should I test Kotlin extension functions?

后端 未结 1 1827
悲哀的现实
悲哀的现实 2021-01-17 08:42

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 ?

1条回答
  •  伪装坚强ぢ
    2021-01-17 09:03

    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);
    

    0 讨论(0)
提交回复
热议问题