Utilizzo JUnit 4, Java 8 e Gradle 1.12. Ho un file con json predefinito che devo caricare. Il mio progetto ha src/main/java/
(contenente la sorgente del progetto), src/main/resources/
(vuoto), src/test/java/
(origine test unità) e src/test/resources/
(il file di dati json per caricare). Il file build.gradle
si trova nella radice.Risorse di accesso nei test unitari
Nel mio codice che ho:
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();
}
}
}
Da quello che ho letto, che mi dovrebbe dare accesso al file di risorse. Tuttavia, ottengo un'eccezione di puntatore nullo quando provo a utilizzare l'URL, poiché la chiamata getSystemResource()
restituisce null.
Come accedere ai miei file di risorse?
Avete la cartella/src/test/risorse nel classpath? –
Ne dubito. Comunque non sto caricando le lezioni. – kwiqsilver