¿Cómo leer un recurso de archivo de texto en Java unit test? [duplicar]


Esta pregunta ya tiene una respuesta aquí:

Tengo una prueba unitaria que necesita para trabajar con el archivo XML ubicado en src/test/resources/abc.xml. ¿Cuál es la forma más fácil de obtener el contenido del archivo en String?

Author: tharindu_DG, 2010-10-08

8 answers

Finalmente encontré una solución limpia, gracias a Apache Commons :

package com.example;
import org.apache.commons.io.IOUtils;
public class FooTest {
  @Test 
  public void shouldWork() throws Exception {
    String xml = IOUtils.toString(
      this.getClass().getResourceAsStream("abc.xml"),
      "UTF-8"
    );
  }
}

Funciona perfectamente. El archivo src/test/resources/com/example/abc.xml está cargado (estoy usando Maven).

Si reemplaza "abc.xml" con, digamos, "/foo/test.xml", este recurso se cargará: src/test/resources/foo/test.xml

También puedes usar Cactoos :

package com.example;
import org.cactoos.io.ResourceOf;
import org.cactoos.io.TextOf;
public class FooTest {
  @Test 
  public void shouldWork() throws Exception {
    String xml = new TextOf(
      new ResourceOf("/com/example/abc.xml") // absolute path always!
    ).asString();
  }
}
 166
Author: yegor256,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-27 12:50:31

Derecho al punto:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/test.xml").getFile());
 75
Author: pablo.vix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-16 10:22:39

Asuma la codificación UTF8 en el archivo - si no, simplemente omita el argumento" UTF8 " y utilizará el conjunto de caracteres predeterminado para el sistema operativo subyacente en cada caso.

Forma rápida en JSE 6 - Simple & no 3rd party library!

import java.io.File;
public class FooTest {
  @Test public void readXMLToString() throws Exception {
        java.net.URL url = MyClass.class.getResource("test/resources/abc.xml");
        //Z means: "The end of the input but for the final terminator, if any"
        String xml = new java.util.Scanner(new File(url.toURI()),"UTF8").useDelimiter("\\Z").next();
  }
}

Camino rápido en JSE 7 (el futuro)

public class FooTest {
  @Test public void readXMLToString() throws Exception {
        java.net.URL url = MyClass.class.getResource("test/resources/abc.xml");
        java.nio.file.Path resPath = java.nio.file.Paths.get(url.toURI());
        String xml = new String(java.nio.file.Files.readAllBytes(resPath), "UTF8"); 
  }

Sin embargo, ninguno de los dos está pensado para archivos enormes.

 47
Author: Glen Best,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-03 20:13:21

Primero asegúrese de que abc.xml se está copiando en su directorio de salida. Entonces debes usar getResourceAsStream():

InputStream inputStream = 
    Thread.currentThread().getContextClassLoader().getResourceAsStream("test/resources/abc.xml");

Una vez que tenga el flujo de entrada, solo necesita convertirlo en una cadena. Este recurso lo explica: http://www.kodejava.org/examples/266.html . Sin embargo, voy a extraer el código relevante:

public String convertStreamToString(InputStream is) throws IOException {
    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(
                    new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {        
        return "";
    }
}
 11
Author: Kirk Woll,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-08 14:14:13

Con el uso de Google Guava:

import com.google.common.base.Charsets;
import com.google.common.io.Resources;

public String readResource(final String fileName, Charset charset) throws Exception {
        try {
            return Resources.toString(Resources.getResource(fileName), charset);
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
}

Ejemplo:

String fixture = this.readResource("filename.txt", Charsets.UTF_8)
 5
Author: Datageek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-15 08:04:03

Puedes intentar hacer:

String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");
 4
Author: Guido Celada,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-31 22:51:00

Esto es lo que usé para obtener los archivos de texto con texto. Usé los pagarés de commons y los Recursos de guayaba.

public static String getString(String path) throws IOException {
    try (InputStream stream = Resources.getResource(path).openStream()) {
        return IOUtils.toString(stream);
    }
}
 1
Author: ikryvorotenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-17 07:59:36

Puede usar una regla Junit para crear esta carpeta temporal para su prueba:

@Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); File file = temporaryFolder.newFile(".src/test/resources/abc.xml");

 1
Author: Igor Ganapolsky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-22 21:05:27