Thursday, February 24, 2011

Finding a file in Unit Tests

A common problem is if you need to access a file in a JUnit test in Eclipse and also in the unit tests run in Hudson.
For Eclipse, if you do

File dir = new File(".");

this directory will point to the root directory of the current project.
So all relative paths should refer to this root directory.

In Hudson, the mapping is not quite the same.


So in my Unit tests I use:

import org.unitils.core.Unitils;
import org.unitils.dbunit.datasetfactory.DataSetResolver;
import org.unitils.dbunit.datasetfactory.impl.DefaultDataSetResolver;

        static DataSetResolver datasetResolver;

 @BeforeClass
 public static void initUnitiles() {
  Unitils unitilsInstance = Unitils.getInstance();
  unitilsInstance.init();
  datasetResolver = new DefaultDataSetResolver();
  datasetResolver.init(unitilsInstance.getConfiguration());
 }

@Test
   public void testIcoli() {

        File file = datasetResolver.resolve(MyTest.class, "sampleFile.xml");


}

and I place the sampleFile.xml in the same directory and the MyTest class...

Go look in the DefaultDataSetResolver code to see how the magic is done... it's quite easy anyway, just do

URL myURL = MyTestClass.getResource("myfile.xml");
File myFile = toFile(myURL);

(where toFile is an Apache Commons function).

No comments: