Pergunta

I want to read a Junit Test for my CsvReader Adapter. It takes filename as argument in constructor. I have placed a file test.txt in src/test/resources for testing purposes, however I can't figure out how to get to this file from test. When I just pass the filename I get FileNotFoundException. I've read about method with class.getClassLoader().getResourceAsStream(name), however I can't pass InputStream instead of filename to constructor, because I need to reopen file several times to get back to the beginning of file after reading it whole. Unfortunately third-party CSVReaders don't take RandomAccessFile as argument and I didn't invent any better solution. So it there always working method to get path to test/resources/file.txt from Junit Test?

Foi útil?

Solução

At runtime, that file doesn't live in test/resources. Your build system/IDE will have put it inside a Jar, or somewhere in your classes/ directory. Either way, it will only be accessible via the classpath; getResourceAsStream() abstracts that away, so that's what you should be using.

If you really need a filename (i.e. if that's an unavoidable aspect of how your class works*), then you should consider using JUnit's @TemporaryFolder rule; have your test setup copy the contents of the resource file into a temporary file, and then pass the name of that to your constructor.


* And that sounds like a design flaw, you should consider rewriting your class to work with abstractions.

Outras dicas

I know that this is an old question and had an answer, but I understand when you want to work with a file path especially when working in JUnit that normally isn't packaged and delivered to the user.

As such here's my way of getting the path for JUnit using Java 8.

 URL resource = this.getClass().getClassLoader().getResource("Name_of_file.csv");
 File file = Paths.get(res.toURI()).toFile();
 String absolutePath = file.getAbsolutePath();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top