Is there a correct way to use the util method to find paths for test resources?
I am writing a small test to read a CSV file (using testng). I found some code to do exactly this and some other lines to find the resources folder.
Now that I reuse this in other scripts, I thought I could just create a utility method instead of copying it:
public static String prepFilepath(Class c) {
URL url = c.getResource("");
String location = url.getPath();
String packageName = c.getPackage().getName().replace(".", "/");
int l = location.lastIndexOf(packageName);
return location.substring(0, l);
}
and it is called by my test like this:
@Test
public void testImport(){
File testFile = new File(ImportUtils.prepFilepath(this.getClass()), inputFileName);
//...
}
However, I don't know if this is correct:
- Can a class reference be passed as a parameter? (I've never done this before for such a small purpose.)
- Are there any more elegant ways?
- Is it good enough to justify use?
Edit: I am using testng
+3
olliaroa
source
to share
1 answer
If the file is in the same package as the class, we can get the url of that file
URL url = getClass().getResource(fileName);
if we need to get a file from a url we can do it this way
File file = new File(url.toURI());
0
Evgeniy Dorofeev
source
to share