如何从Kotlin的资源中读取文本文件?

我想在Kotlin写一个Spek测试。 测试应从src/test/resources文件夹读取HTML文件。 怎么做?

 class MySpec : Spek({ describe("blah blah") { given("blah blah") { var fileContent : String = "" beforeEachTest { // How to read the file file.html in src/test/resources/html fileContent = ... } it("should blah blah") { ... } } } }) 

 val fileContent = MySpec::class.java.getResource("/html/file.html").readText() 

稍有不同的解决方案:

 class MySpec : Spek({ describe("blah blah") { given("blah blah") { var fileContent = "" beforeEachTest { html = this.javaClass.getResource("/html/file.html").readText() } it("should blah blah") { ... } } } }) 

另一个稍微不同的解

 @Test fun basicTest() { "/html/file.html".asResource { // test on `it` here... println(it) } } fun String.asResource(work: (String) -> Unit) { val content = this.javaClass::class.java.getResource(this).readText() work(content) }