0

I need to write a Unittest for the following method, simulating the the file/Directory accessed is somehow not readable fpr the application:

public void writeFile(String path) {
    File f = new File(path); 
    //some stuff...
}

How do i unittest this setup, if i can only provide a Path and cannot influence or even KNOW (blackbox) how the Developer of "writeFile(String path)" implemented the file access, i only know the Method signature and that a file is read.

basically, i need to know if it is possible to make JUnit "intercept" request to the filesystem and react depending on what path is to be accessed. Or is the only possibility to actually create a file in the unittest, that is inaccesible to the Unittest itself? In that case, how can the unittest "clean up" after itself?

I am open to all solution that utilize common Mocking frameworks or JUnit.

thanks in advance,

BillDoor

billdoor
  • 1,999
  • 4
  • 28
  • 54
  • 2
    The standard way would be to change the method signature to accept a `File` instead of a `String`. Is that a possibility? – Keppil Sep 15 '14 at 13:54
  • It would be, but it seems strange to me, having to change "real" code, to fit the "testing needs". The decision makers will think this is strange practice too – billdoor Sep 15 '14 at 13:57
  • 2
    You can't just write the code in any way you like and expect it to be testable. You need to keep it in mind when designing the methods. Here that clearly wasn't the case, so changing the method to make it testable is a Good Thing. – Keppil Sep 15 '14 at 14:00
  • i'll keep it in mind and bring this up thanks! still i am interested if there is a possibility to handle this if i had no means whatsoever to influence the developers – billdoor Sep 15 '14 at 14:04
  • possible duplicate of [How do I unit-test saving file to the disk?](http://stackoverflow.com/questions/3381801/how-do-i-unit-test-saving-file-to-the-disk) – Raedwald Sep 19 '14 at 11:48

1 Answers1

0

Basically, you can't. There are two issues:

  1. Unit testing/mocking isn't a black box test, to some extent you have to know what's going on inside the function you are testing.

  2. There is no general mechanism for mocking out calls that the developer may write. Functions need to be written to be testable. If the developer doesn't do that, don't expect to be able to write a decent unit test for it.

Realistically you would have to write more of an integration: pass in a valid path, call the function, check the file exists, delete the file. Similarly you can pass an invalid path add make sure you get the expected behaviour.

If you want to experiment a bit, you could try and use jimfs or even try and use AspectJ to intercept calls to the file system APIs. However neither of them is realistic in this case and the real solution is to get the developer to write testable code.

matt helliwell
  • 2,574
  • 16
  • 24