2017-03-11 5 views
11

मैं कोटलिन में एक स्पेक टेस्ट लिखना चाहता हूं। परीक्षण को 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") { 
       ... 
      } 
     } 
    } 
}) 

उत्तर

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

मुझे इस काम नहीं किया के लिए, मैं इस 'को बदलना पड़ा: : class.java.classLoader.getResource ("/ html/file.html")। readText() ' – pk1914

+0

मेरे लिए ये दोनों विकल्प एंड्रॉइड ऐप में काम करते हैं (उनमें से एक में अतिरिक्त'/'देखें, डब्ल्यू जिसे दूसरे में हटा दिया जाना है): 'this :: class.java.getResource ("/html/file.html ")। readText()' और '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/resource' में एक परीक्षण इनपुट फ़ाइल बनाने के बाद, '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) 
} 
संबंधित मुद्दे