0

My program needs to interact to a directory (with a hierarchical structure) a lot and I need to test it. Therefore, I need to create a directory (and then create sub dirs and files) during the JUnit and then delete this directory after the test.

Is there a good way to do this conveniently?

chen
  • 4,302
  • 6
  • 41
  • 70

4 Answers4

2

Look at the methods on java.io.File. If it isn't a good fit, explain why.

Ed Staub
  • 15,480
  • 3
  • 61
  • 91
  • createTempFile? I want to delete the directory right after my unit test, and this does not seem to do so. – chen Jul 10 '11 at 00:41
  • OK, then you're looking for something that will delete it automatically for you-yes? – Ed Staub Jul 10 '11 at 01:46
1

You should create your test directory structure in the BeforeClass/Before JUnit annotated methods and remove them in AfterClass/After (have a look at the JUnit FAQ, e.g. How can I run setUp() and tearDown() code once for all of my tests?).

If java.io.File does not offer all you need to prepare your directory structure have a look at com.google.common.io.Files (google guava) or org.apache.commons.io.FileUtils (apache commons io).

FrVaBe
  • 47,963
  • 16
  • 124
  • 157
  • Guava has nothing relevant. apache does... but from chen's comment on mine, looks like your JUnit point is more on point. – Ed Staub Jul 10 '11 at 21:03
  • @Ed Staub Why shouldn't guavas `createParentDirs(File file)`, `createTempDir()`, `deleteDirectoryContents(File directory)` or `deleteRecursively(File file)` be potentially relevant? – FrVaBe Jul 11 '11 at 08:27
  • Oops - missed the create methods somehow - thanks, sorry. I should have known better - whenever I look for anything in Guava that should be there, it nearly always is! – Ed Staub Jul 11 '11 at 12:22
1

If you can use JUnit 4.7, you can use the TemporaryFolder rule:

@RunWith(JUnit4.class)
public class FooTest {
  @Rule
  public TemporaryFolder tempFolder = new TemporaryFolder();

  @Test
  public void doStuffThatTouchesFiles() {
    File root = tempFolder.newFolder("root");
    MyProgram.setRootTemporaryFolder(root);

    ... continue your test
  }
}

You could also use the Rule in an @Before method. Starting with JUnit 4.9, you will be make the rule field a static, so you could use the rule in a @BeforeClass method.

See this article for details

NamshubWriter
  • 23,549
  • 2
  • 41
  • 59
0

You can just create a tem directory. Take a look at How to create a temporary directory/folder in Java?

If you need to remotely create a directory, connect ssh and do a ssh command

Some ssh libs SSH Connection Java

Community
  • 1
  • 1
Diego Dias
  • 21,634
  • 6
  • 33
  • 36