web-dev-qa-db-fra.com

Comment lire une ressource de fichier texte dans le test unitaire Java?

J'ai un test unitaire qui doit fonctionner avec un fichier XML situé dans src/test/resources/abc.xml. Quel est le moyen le plus simple de récupérer le contenu du fichier dans String?

186
yegor256

Enfin, j'ai trouvé une solution intéressante, grâce à 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"
    );
  }
}

Fonctionne parfaitement. Le fichier src/test/resources/com/example/abc.xml est chargé (j'utilise Maven).

Si vous remplacez "abc.xml" par, par exemple, "/foo/test.xml", cette ressource sera chargée: src/test/resources/foo/test.xml

Vous pouvez également utiliser 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();
  }
}
201
yegor256

Droit au point :

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/test.xml").getFile());
100
pablo.vix

Supposons le codage UTF8 dans le fichier - sinon, laissez simplement de côté l’argument "UTF8" et utilisera le jeu de caractères par défaut pour le système d’exploitation sous-jacent dans chaque cas.

moyen rapide dans JSE 6 - Simple et aucune bibliothèque tierce partie!

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();
  }
}

moyen rapide dans JSE 7 (le futur)

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"); 
  }

Ni destiné à d'énormes fichiers cependant.

53
Glen Best

Tout d’abord, assurez-vous que abc.xml est copié dans votre répertoire de sortie. Ensuite, vous devriez utiliser getResourceAsStream():

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

Une fois que vous avez InputStream, il vous suffit de le convertir en chaîne. Cette ressource le précise: http://www.kodejava.org/examples/266.html . Cependant, je vais extraire le code correspondant:

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 "";
    }
}
13
Kirk Woll

Avec l'utilisation 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);
        }
}

Exemple:

String fixture = this.readResource("filename.txt", Charsets.UTF_8)
8
Datageek

Vous pouvez essayer de faire:

String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");
5
Guido Celada

Vous pouvez utiliser une règle Junit pour créer ce dossier temporaire pour votre test:

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

1
IgorGanapolsky

Voici ce que j'ai utilisé pour obtenir les fichiers texte avec du texte. J'ai utilisé les ressources communes et les ressources de goyave.

public static String getString(String path) throws IOException {
    try (InputStream stream = Resources.getResource(path).openStream()) {
        return IOUtils.toString(stream);
    }
}
1
ikryvorotenko