简体   繁体   中英

Mocking / Unittesting file operation

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

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.

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