मैं जुनीट 4, जावा 8 और ग्रैडल 1.12 का उपयोग कर रहा हूं। मेरे पास डिफ़ॉल्ट जेसन के साथ एक फ़ाइल है जिसे मुझे लोड करने की आवश्यकता है। मेरी परियोजना में src/main/java/
(प्रोजेक्ट स्रोत शामिल है), src/main/resources/
(खाली), src/test/java/
(इकाई परीक्षण स्रोत), और src/test/resources/
(जेसन डेटा फ़ाइल लोड करने के लिए) निर्देशिकाएं हैं। build.gradle
फ़ाइल रूट में है।यूनिट टेस्ट में एक्सेस संसाधन
मेरी कोड में मेरे पास है:
public class UnitTests extends JerseyTest
{
@Test
public void test1() throws IOException
{
String json = UnitTests.readResource("/testData.json");
// Do stuff ...
}
// ...
private static String readResource(String resource) throws IOException
{
// I had these three lines combined, but separated them to find the null.
ClassLoader c = UnitTests.class.getClassLoader();
URL r = c.getSystemResource(resource); // This is returning null. ????
//URL r = c.getResource(resource); // This had the same issue.
String fileName = r.getFile();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName)))
{
StringBuffer fileData = new StringBuffer();
char[] buf = new char[1024];
int readCount = 0;
while ((readCount = reader.read(buf)) != -1)
{
String readData = String.valueOf(buf, 0, readCount);
fileData.append(readData);
}
return fileData.toString();
}
}
}
मैं क्या पढ़ा से, कि मुझे संसाधन फ़ाइल के लिए उपयोग करना चाहिए। हालांकि, जब मैं यूआरएल का उपयोग करने की कोशिश करता हूं, तो मुझे एक शून्य सूचक अपवाद मिलता है, क्योंकि getSystemResource()
कॉल रिटर्न शून्य देता है।
मैं अपनी संसाधन फ़ाइलों को कैसे एक्सेस करूं?
आप अपने classpath में/src/परीक्षण/संसाधन फ़ोल्डर है? –
मुझे शक है। हालांकि मैं कक्षाएं लोड नहीं कर रहा हूं। – kwiqsilver