I want to write a Spek test in Kotlin. The test should read an HTML file from the src/test/resources
folder. How to do it?
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()
another slightly different solution:
@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)
}
A slightly different solution:
class MySpec : Spek({
describe("blah blah") {
given("blah blah") {
var fileContent = ""
beforeEachTest {
html = this.javaClass.getResource("/html/file.html").readText()
}
it("should blah blah") {
...
}
}
}
})
No idea why this is so hard, but the simplest way I've found (without having to refer to a particular class) is:
fun getResourceAsText(path: String): String {
return object {}.javaClass.getResource(path).readText()
}
And then passing in an absolute URL, e.g.
val html = getResourceAsText("/www/index.html")