Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileNotFoundException - java test resources [duplicate]

I am writing junit tests, where I need to read a file from src/test/resources

I have a following code in my src/test/java/some_packages/UserTests:

InputStream inputStream = new FileInputStream(new File("abc.txt"));

The file is of course present, but when I run my test I get java.io.FileNotFoundException: abc.txt (No such file or directory)

I marked resources folder as test resources in intellij

like image 260
Pond Avatar asked Dec 19 '22 18:12

Pond


1 Answers

new File("abc.txt") is relative to the working directory for your tests, not the src/test/resources directory. To access resources in the src/test/resources directory, get the resource from the class loader:

InputStream inputStream = getClass().getResourceAsStream("/abc.txt");
like image 195
Darth Android Avatar answered Dec 21 '22 11:12

Darth Android