简体   繁体   中英

Suggestions for a java Mock File (to mock java.io.File)

Does anyone have suggestions for a java mock File object? I Am using a thirdparty class which need to get a java.io.File object as argument. I receive the data for this file in a stream over a webservice (also one of their products).

One solution is to write all this data to a file and offer this to the class. This is a solution I don't like: it takes away the advantage of using the webservice in stead of just downloading the file.

Quicker and more efficient would be to put this data from memory in a Mock File and offer this Mock File to the thirdparty class.

It would probably have to be a MockFile extending the java.io.File and overriding all the functions that do actual interfacing with the file on the hard disk.

I know the thirdparty should have used a stream as an input argument in stead of a file. However, this is beyond my influence.

This is just a suggestion based on my understanding of your question. I believe, you must be doing something like this,

public void doSomething(){
      //Pre processing
       Object result=new ThirdPartyCode().actualMethod(file);
     //Post processing
}

Mock objects make more sense from an unit testing perspective. Your objective is not to unit test the third party library function.Whereas it is to unit test doSomething() method. So probably you can create a wrapper around the third party function.Maybe something like this,

public class Wrapper implements MyWrapper{

   public Object invokeThirdPartyFunction(File file){
      new ThirdPartyCode().actualMethod(file);
   }
}

Now you can create a mock wrapper(implementing the same interface) and use this mock wrapper for all your junit cases.

Does the tested class only query the mock File's name, attributes etc., or does it actually attempt to open the file?

In the former case, you can easily create your mock using eg EasyMock or an equivalent mocking framework.

The latter case is more tricky, and I am afraid if the input stream is created internally by the class, you have no choice other than actually creating a real test file on the HD.

You could load the 3rd party code using an ASM based classloader that maps java.io.File to your own "fake" implementation. It's a bit of work, and needs to be performed carefully... For example you will need to also map FileInputStream , etc.

You don't use file (or any external dependency in Unit tests). Except using mocks, your approaches will result in problematic tests. See this javaranch article for more

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