简体   繁体   中英

Is there a correct way to have a util method to find test resource paths?

I am writing a small test to read a CSV file (using testng). I found some code to do just that and some other lines to find the resource folder itself.

Now as I am re-using this in other scenarios, I thought that I could just create a util method instead of copy pasting:

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 it is the correct way:

  • Is it ok to pass a class reference as parameter? (I had never done that before for such a small purpose)
  • Are there more elegant ways?
  • Is it generic enough to justify the util?

Edit: I am using testng

If the file is in the same package as the class then we can get URL to the file this way

URL url = getClass().getResource(fileName);

if we need to get File from URL we can do it this way

File file = new File(url.toURI());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM