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({
Kotlin + Spring way:
@Autowired
private lateinit var resourceLoader: ResourceLoader
fun load() {
val html = resourceLoader.getResource("classpath:html/file.html").file
.readText(charset = Charsets.UTF_8)
}
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")
Using Google Guava library Resources class:
import com.google.common.io.Resources;
val fileContent: String = Resources.getResource("/html/file.html").readText()
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") {
...
}
}
}
})
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)
}