Ответ 1
val fileContent = MySpec::class.java.getResource("/html/file.html").readText()
Я хочу написать тест Spek в Котлине. Тест должен прочитать HTML файл из папки src/test/resources
. Как это сделать?
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()
другое немного другое решение:
@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)
}
Несколько другое решение:
class MySpec : Spek({
describe("blah blah") {
given("blah blah") {
var fileContent = ""
beforeEachTest {
html = this.javaClass.getResource("/html/file.html").readText()
}
it("should blah blah") {
...
}
}
}
})
Не знаю, почему это так сложно, но самый простой способ, который я нашел (без необходимости ссылаться на определенный класс):
fun getResourceAsText(path: String): String {
return object {}.javaClass.getResource(path).readText()
}
А затем передать абсолютный URL, например,
val html = getResourceAsText("/www/index.html")
Котлин + Весенний путь:
@Autowired
private lateinit var resourceLoader: ResourceLoader
fun load() {
val html = resourceLoader.getResource("classpath:html/file.html").file
.readText(charset = Charsets.UTF_8)
}
val fileContent = javaClass.getResource("/html/file.html").readText()
Вы можете найти класс File полезным:
import java.io.File
fun main(args: Array<String>) {
val content = File("src/main/resources/input.txt").readText()
print(content)
}
Использование ресурсов библиотеки Google Guava:
import com.google.common.io.Resources;
val fileContent: String = Resources.getResource("/html/file.html").readText()