0

I need to pass a File to a class for unit tests. The class requires a File specifically, and can't be modified - it just reads it. (So I don't want to try to mock out that class or modify it - just pass it the File it needs.)

What's the recommended way to do this?

I put the file in src/test/resources/... and just passed that entire path in, and, since the test is run in the project root dir, this works. But this seems quite wrong.

UPDATE: To emphasize - the class needs a File object, not an InputStream or anything else.

SRobertJames
  • 6,827
  • 12
  • 48
  • 89
  • possible duplicate of [Java resource as file](http://stackoverflow.com/questions/676097/java-resource-as-file) – Noah Jul 10 '14 at 01:53
  • @Noah - that Java question talks about getting an InputStream, I need a File object specifically – SRobertJames Jul 10 '14 at 02:18
  • what about this one? http://stackoverflow.com/questions/4359876/how-to-load-reference-a-file-as-a-file-instance-from-the-classpath – Noah Jul 10 '14 at 13:11

3 Answers3

0

this.getClass().getResourceAsStream(fileName) is recommended way to read files from resources

wedens
  • 1,646
  • 13
  • 16
0

If you need to look up something on the classpath and have it returned as a File, try this:

import java.net.URL
import java.io.File

object Test extends App {
  val fileUrl: URL = getClass.getResource("Test.class")
  val file : File = new File(fileUrl.toURI())
  println(s"File Path: ${file.getCanonicalPath}")
}

It more or less uses all Java classes, but it works. In my example, the Test object is finding its own compiled classfile, but you can obviously change it to whatever you want.

Todd
  • 26,412
  • 10
  • 67
  • 80
0

The JVM doesn't have a concept of getting a classpath resource as a File because resources don't necessarily correspond to files. (Often they're contained in jars.)

Your test could start by getting an InputStream and copying it into a temporary file.

Chris Martin
  • 28,558
  • 6
  • 66
  • 126