Java Unit Testing – Writing Unit Test Cases for File Format Converter Utility

javajunitunit testing

I have created one utility module which converts one file format to another one. File i.e. test.abc will be converted to i.e. test.pqr and internal format of files are totally different. This module involves nearly 5 different file formats.

Internally, it uses one native tool and I do not have any control over it. It converts the file and my utility class just sends commands to this tool and manipulates files.

public class Utility {

     public File convertIt(File file, Format to) {
        // Check extension
        // Execute command of native tool accordingly
        // Return resulting file
     }
}

I am not able to conclude how should I write unit test cases for this utility. Because each format is different and on production every file will be inserted by user. Moreover, there are lot of attributes some are mandatory and some are optional. and it may be possible one file format may use it or may not.

Currently what I am thinking is, in test case resources, I can supply all the input files and resulting files which I already have. Then I can just compare output of each call with existing output file. But I think this will not cover all the scenarios and I may need more files for testing.

- resources
       |- input
            |- input1.abc
            |- input2.pqr
            |- input3.xyz
       |- output
            |- output1.xyz
            |- output2.abc
            |- output3.pqr

My questions,

  • Is this approach correct ?
  • Is there any other better approach ?
  • What is the best practice to test such methods which manipulates files ?

Best Answer

I want to test my code which is basically a wrapper of native tool.

Perfect. If you wanted to test the native tool you wouldn't do that via your code in any case. So you don't have to create input files or output files. All you have to do is ensure that the native tool is called with the correct arguments.

One way is to create an Executor class that can execute a command, and pass it into your converter.

class Converter {
    private Executor executor;

    public Converter(Executor executor) {
        this.executor = executor;
    }

    convertIt() {
        command = ...
        executor.execute(command);
    }
}

}

Then use use Mockito to create a mock Executor for testing. Use junit to make it easy to create and run test methods.

import org.junit.Test;
import static org.mockito.Mockito.*;

class ConverterTest {
    private Executor executor;

    @Before
    public void setup() {
         executor = mock(Executor.class);
    }

    @Test
    public void TestAtoB() {
        String expectedCommand = ...;
        Converter converter = new Converter(executor);
        converter.convert(...);
        verify(executor).execute(expectedCommand);
    }
}