Can somebody suggest an easy way to get a reference to a file as a String/InputStream/File/etc type object in a junit test class? Obviously I could paste the file (xml in this case) in as a giant String or read it in as a file but is there a shortcut specific to Junit like this?
public class MyTestClass{
@Resource(path="something.xml")
File myTestFile;
@Test
public void toSomeTest(){
...
}
}
If you need to actually get a
File
object, you could do the following:Which has the benefit of working cross platform, as described in this blog post.
You can try doing:
If you want to load a test resource file as a string with just few lines of code and without any extra dependencies, this does the trick:
"\\A" matches the start of input and there's only ever one. So this parses the entire file contents and returns it as a string. Best of all, it doesn't require any 3rd party libraries (like IOUTils).
I know you said you didn't want to read the file in by hand, but this is pretty easy
All you have to do is ensure the file in question is in the classpath. If you're using Maven, just put the file in src/test/resources and Maven will include it in the classpath when running your tests. If you need to do this sort of thing a lot, you could put the code that opens the file in a superclass and have your tests inherit from that.
You can try
@Rule
annotation. Here is the example from the docs:You just need to create
FileResource
class extendingExternalResource
.Full Example