Two Laptop Bag
The moose likes I/O and Streams and the fly likes Wait for file to be completely written Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Wait for file to be completely written" Watch "Wait for file to be completely written" New topic

Wait for file to be completely written

Alexander D�ubler

Joined: Feb 15, 2006
Posts: 11
Hi everyone,

I have the following question:

in one of our JUnit tests we use a printer driver to print to a file. However, we have to wait for this file to be completely written before we can continue the test-process. How can I ensure that the target file has been written completely?

Thanks a lot,
Serkan Demir
Ranch Hand

Joined: Feb 03, 2005
Posts: 61
A unit test should not test whether a file is printed or not. A unit test should not depend external devices, machines, DBs etc.. and should run anywhere quickly .
Please try to mock printer or printer driver in your unit tests.

A guy from Turkey<br /><a href="" target="_blank" rel="nofollow"></a>
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
That fits Michael Feathers's definitions in It's not a unit test if ... and sure enough if you're testing the document generation you don't really need the printer driver. Let us know if that's the case and we can discuss mock objects.

But if the goal is to test the driver or if you can't change the code that calls it, you can't very well mock the driver out. Maybe we just have to call it something other than "unit" test.

So, I guess the driver runs on another thread, maybe even the OS print spooler? If you run the thread you can join() it to know when it's done. If not, the crude way to tell when it's probably done is to check the file every second or two and see when it stops getting bigger. It would be cool to find an API into the print queue or something that you could query or register for events but that could wind up taking more code than the class youre trying to test.

What have you tried so far?

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Per Wramdemark

Joined: May 04, 2006
Posts: 2
I am facing the exact problem. I want to write a unit test but understand that I shouldn't include writing to disc in my unit testing. But still I want to test my that does the actual writing. Does there exists any memory File handling that could be used instead? Any pointer or tips?


I agree. Here's the link:
subject: Wait for file to be completely written
It's not a secret anymore!