views:

50

answers:

2

we have code that persists a file and I would like to check the content of the file during testing. I though that such scenario will be best implemented if I abstract the file persistence operation to the following interface:

public interface IFilePersist
{
   void Save(XXX, FileLocation);
}

In unit testing I will inject the mock that will check the content and in production the interface will be actually persist to right location.

Is it an overhead? Is this practice commonly used? For DB related operations this kind of operation is trivial and always used.

+1  A: 

Yes, that's one way to do it, if you want to reduce overhead of creating a tracking mock object you may also do a local override of the method if possible. I don't know what language you're using, but in Java a local override would look like this:

// actual class
public class SomeClass {
    public void method() {
     System.out.println("Hello!");
    }
}

// creating the class in test

SomeClass c = new SomeClass() {
public void method() {
     System.out.println("Hi!");
    }  
};

Now your class actually prints "Hi!" when m() is called because it's overriden in an anonymous inner class whilst the actual production class still keeps printing "Hello!".

Esko
+1  A: 

Yes, it's good to keep unit tests isolated from file system. First because file system access is slower than memory access. Then one can run into other problems (permissions, missing path, FS full or not mounted ...).

The real persistence, on the file system, shall be tested with integration tests.

philippe