如何在同一个文件中为Kotlin代码添加unittest并运行它?

我有这样的代码:

class Solution { fun strStr(haystack: String, needle: String): Int { return haystack.indexOf(needle) } } 

在Python中,通常我可以在同一个文件中添加一些测试,并添加如下内容:

  if __name__ == '__main__': unittest.main() 

运行unit testing。 我如何在Kotlin中实现同样的目标?

测试通常放在Kotlin / Java项目中的单独模块的原因是,测试通常需要一些额外的依赖项,这些依赖项对于生产代码是没有意义的,比如JUnit或其他库。 另外,在同一个文件中编写的测试会被编译成一个类,它是生产代码输出的一部分。

在已发布并用作其他项目的依赖项目中,请考虑不要混合生产和测试代码。

当然,您可以将这些测试依赖项添加到生产代码中。 作为JUnit的例子,在IntelliJ项目中添加依赖项(在Gradle项目中: dependencies { compile 'junit:junit:4.12' } : 请参阅参考资料 ),然后添加一个带有@Test函数的测试类:

 import org.junit.Test import org.junit.Assert class Solution { fun strStr(haystack: String, needle: String): Int { return haystack.indexOf(needle) } } class SolutionTest { @Test fun testSolution() { val text = "hayhayhayneedlehayhay" val pattern = "needle" val result = strStr(text, pattern) Assert.assertEquals(8, result) } }