2017-03-11 18 views
11

나는 Kotlin에서 Spek 테스트를 쓰고 싶다. 테스트는 src/test/resources 폴더에서 HTML 파일을 읽어야합니다. 그것을하는 방법?Kotlin의 리소스에서 텍스트 파일을 읽는 방법은 무엇입니까?

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") { 
       ... 
      } 
     } 
    } 
}) 

답변

20
val fileContent = MySpec::class.java.getResource("/html/file.html").readText() 
+3

이 날이 작동하지 않았다 들어 나는이'으로 변경했다 : : class.java.classLoader.getResource ("/ html/file.html"). readText()' – pk1914

+0

나를 위해이 두 가지 옵션은 안드로이드 애플 리케이션에서 작동했다. html은 다른 곳에서 삭제되어야한다) :'this :: class.java.getResource ("/ html/file.html"). readText()'and this :: class.java.classLoader.getResource ("html/file.html "). readText()' – Franco

8

약간 다른 솔루션 :

class MySpec : Spek({ 
    describe("blah blah") { 
     given("blah blah") { 

      var fileContent = "" 

      beforeEachTest { 
       html = this.javaClass.getResource("/html/file.html").readText() 
      } 

      it("should blah blah") { 
       ... 
      } 
     } 
    } 
}) 
+0

웬일인지 이것이 나를 위해 작동하지 않았다. 클래스를 명시 적으로 호출하면됩니다. 그냥 다른 사람들을 위해 추가. 나는 그것이 tornadofx와 관련이 있다고 생각한다. – nmu

+0

'/ src/test/resources'에 테스트 입력 파일을 만든 후,'this.javaClass.getResource ("/ <테스트 입력 파일명>")'이 예상대로 작동했다. 위의 솔루션에 감사드립니다. – jkwuc89

6

다른 약간 다른 솔루션 :

@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) 
} 
관련 문제