我想在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") {
...
}
}
}
})
Run Code Online (Sandbox Code Playgroud)
JB *_*zet 90
val fileContent = MySpec::class.java.getResource("/html/file.html").readText()
Run Code Online (Sandbox Code Playgroud)
jho*_*ges 24
另一个略有不同的解
@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)
}
Run Code Online (Sandbox Code Playgroud)
Rus*_*ggs 15
不知道为什么这么难,但我发现的最简单的方法(无需引用特定的类)是:
fun getResourceAsText(path: String): String {
return object {}.javaClass.getResource(path).readText()
}
Run Code Online (Sandbox Code Playgroud)
然后传入绝对URL,例如
val html = getResourceAsText("/www/index.html")
Run Code Online (Sandbox Code Playgroud)
Ola*_*laf 12
略有不同的解决方案:
class MySpec : Spek({
describe("blah blah") {
given("blah blah") {
var fileContent = ""
beforeEachTest {
html = this.javaClass.getResource("/html/file.html").readText()
}
it("should blah blah") {
...
}
}
}
})
Run Code Online (Sandbox Code Playgroud)
这是我更喜欢的方式:
fun getResourceText(path: String): String {
return File(ClassLoader.getSystemResource(path).file).readText()
}
Run Code Online (Sandbox Code Playgroud)
使用谷歌番石榴库资源类:
import com.google.common.io.Resources;
val fileContent: String = Resources.getResource("/html/file.html").readText()
Run Code Online (Sandbox Code Playgroud)
val fileContent = javaClass.getResource("/html/file.html").readText()
Run Code Online (Sandbox Code Playgroud)
private fun loadResource(file: String) = {}::class.java.getResource(file).readText()
Run Code Online (Sandbox Code Playgroud)
Kotlin + Spring方式:
@Autowired
private lateinit var resourceLoader: ResourceLoader
fun load() {
val html = resourceLoader.getResource("classpath:html/file.html").file
.readText(charset = Charsets.UTF_8)
}
Run Code Online (Sandbox Code Playgroud)
这个顶级 kotlin 函数在任何情况下都可以完成这项工作
fun loadResource(path: String): URL {
return Thread.currentThread().contextClassLoader.getResource(path)
}
Run Code Online (Sandbox Code Playgroud)
或者如果你想要一个更强大的功能
fun loadResource(path: String): URL {
val resource = Thread.currentThread().contextClassLoader.getResource(path)
requireNotNull(resource) { "Resource $path not found" }
return resource
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
43623 次 |
最近记录: |