Quiero escribir una prueba Spek en Kotlin. La prueba debe leer un archivo HTML de la carpeta src/test/resources . ¿Cómo hacerlo?
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()
Una solución ligeramente diferente:
class MySpec : Spek({ describe("blah blah") { given("blah blah") { var fileContent = "" beforeEachTest { html = this.javaClass.getResource("/html/file.html").readText() } it("should blah blah") { ... } } } })otra solución ligeramente diferente:
@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) }No tengo idea de por qué esto es tan difícil, pero la forma más sencilla que he encontrado (sin tener que referirme a una clase en particular) es:
fun getResourceAsText(path: String): String? = object {}.javaClass.getResource(path)?.readText() Devuelve null si no se encuentra ningún recurso con este nombre ( como se documenta ).
Y luego pasar una URL absoluta, por ejemplo
val html = getResourceAsText("/www/index.html")!!val fileContent = javaClass.getResource("/html/file.html").readText()
Kotlin + Manera de primavera:
@Autowired private lateinit var resourceLoader: ResourceLoader fun load() { val html = resourceLoader.getResource("classpath:html/file.html").file .readText(charset = Charsets.UTF_8) }Puede encontrar útil la clase File:
import java.io.File fun main(args: Array<String>) { val content = File("src/main/resources/input.txt").readText() print(content) }Uso de la clase de recursos de la biblioteca de guayaba de Google:
import com.google.common.io.Resources; val fileContent: String = Resources.getResource("/html/file.html").readText()private fun loadResource(file: String) = {}::class.java.getResource(file).readText()
Esta es la forma en que yo prefiero hacerlo:
fun getResourceText(path: String): String { return File(ClassLoader.getSystemResource(path).file).readText() }esta función de kotlin de nivel superior hará el trabajo en cualquier caso
fun loadResource(path: String): URL { return Thread.currentThread().contextClassLoader.getResource(path) }o si quieres una función más robusta
fun loadResource(path: String): URL { val resource = Thread.currentThread().contextClassLoader.getResource(path) requireNotNull(resource) { "Resource $path not found" } return resource }FYI: En todos los casos anteriores. getResource() es una forma insegura de usar anulable.
No lo he probado localmente, pero prefiero de esta manera:
fun readFile(resourcePath: String) = String::class.java.getResource(resourcePath)?.readText() ?: "<handle default. or handle custom exception>"O incluso como función de tipo de datos personalizado
private fun String.asResource() = this::class.java.getResource(resourcePath)?.readText() ?: "<handle default. or handle custom exception>"y luego puede llamar directamente en la ruta como:
// For suppose val path = "/src/test/resources" val content = path.asResource()