4

Using Java 8.

Basically, in a unit test (junit) I have this code:

callSomeCode();
assertTrue(new File(this.getClass().getResource("/img/dest/someImage.gif").getFile()).exists());

In callSomeCode(), I have this:

InputStream is = bodyPart.getInputStream();
File f = new File("src/test/resources/img/dest/" + bodyPart.getFileName()); //filename being someImage.gif
FileOutputStream fos = new FileOutputStream(f);
byte[] buf = new byte[40096];
int bytesRead;
while ((bytesRead = is.read(buf)) != -1)
   fos.write(buf, 0, bytesRead);
fos.close(); 

The first time the test runs, this.getClass().getResource("/img/dest/someImage.gif")returns null although the file is well created.

The second time (when the file was already created during the first test run then just overwritten), it is non-null and the test passes.

How to make it work the first time?
Should I configure a special setup in IntelliJ to automatically refresh the folder where the file is created?

Note that I have this basic maven structure:

--src
----test
------resources   
Mik378
  • 21,881
  • 15
  • 82
  • 180

2 Answers2

3

As the comment by nakano531 points out - your problem is not with the file system, but with the classpath. You're trying to read your file using a classloader by invoking the getClass().getResource(...) methods rather than reading the file using classes that access the file system directly.

For example, if you had written your test like this:

callSomeCode();
File file = new File("src/test/resources/img/dest/someImage.gif");
assertTrue(file.exists());

You wouldn't have had the issue you're having now.

Your other option is to implement the solution from the link that nakano531 provided: https://stackoverflow.com/a/1011126/1587791

Community
  • 1
  • 1
D.B.
  • 4,523
  • 2
  • 19
  • 39
0

i was stuck in the same situation, a way out is to delay the execution of line where it reads from the file which is created during run time. use this:

callSomeCode();
Thread.sleep(6000);
assertTrue(new File(this.getClass().getResource("/img/dest/someImage.gif").getFile()).exists());
Ganesh Bhat
  • 246
  • 4
  • 19