This is a
TestWatcher which is used to create and delete sub directories before and after unit tests respectively.
Ideally a
SubDirTestWatcher would be used in conjunction with a
DirTestWatcher or a sub class of
DirTestWatcher. The
DirTestWatcher would be used to create the base directory used by the
SubDirTestWatcher to create all its sub directories. Here
is an example of using the
SubDirTestWatcher in this way.
package my.proj;
public class MyTestClass {
public static final String TEST_SUB_DIR = "testSubDir";
private static File testSubDir;
@org.junit.ClassRule
public static final DirTestWatcher dirTestWatcher = new DirTestWatcher();
@org.junit.BeforeClass
public static void setupFiles() {
testSubDir = new File(dirTestWatcher.getDir(), TEST_SUB_DIR);
}
@org.junit.Rule
public final SubDirTestWatcher subDirTestWatcher =
new SubDirTestWatcher.Builder(dirTestWatcher.getDir())
.addSubDir(TEST_SUB_DIR)
.build();
@org.junit.Test
public void myTestMethod1() {
// The testSubDir should be created for us by the SubDirTestWatcher
org.junit.Assert.assertTrue(testSubDir.exists());
// Lets make another sub directory in our sub directory
File newSubDirectory = new File(testSubDir, "a");
newSubDirectory.mkdirs();
org.junit.Assert.assertTrue(newSubDirectory.exists());
}
@org.junit.Test
public void myTestMethod2() {
// The testSubDir should be created for us by the SubDirTestWatcher
org.junit.Assert.assertTrue(testSubDir.exists());
// The directory we created in the previous test should be gone
org.junit.Assert.assertFalse(new File(testSubDir, "a").exists());
}
}