我应该如何测试Kotlin扩展功能? [英] How should I test Kotlin extension functions?

查看:108
本文介绍了我应该如何测试Kotlin扩展功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我如何在Kotlin中对扩展功能进行单元测试吗?由于它们是静态解析的,应该将它们作为静态方法调用还是作为非静态方法进行测试?另外,由于语言可以与Java完全互操作,因此应该如何对Kotlin扩展功能执行Java单元测试?

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 ?

推荐答案

好,要测试一种方法(无论是否静态),请像实际代码一样调用它,然后检查它是否做对了.

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.

例如,假设此扩展方法在com/foo/Bar.kt文件中定义:

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

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

如果您使用Kotlin编写测试(通常会用来测试Kotlin代码),那么您将编写

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

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

如果您使用Java编写(但是为什么要这么做?)

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

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

这篇关于我应该如何测试Kotlin扩展功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆