chen
chen

Reputation: 4490

how to test file system related behavior and delete the created dir

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?

Upvotes: 0

Views: 4108

Answers (4)

NamshubWriter
NamshubWriter

Reputation: 24286

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

Upvotes: 1

FrVaBe
FrVaBe

Reputation: 49341

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).

Upvotes: 1

Diego Dias
Diego Dias

Reputation: 22606

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

Upvotes: 0

Ed Staub
Ed Staub

Reputation: 15690

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

Upvotes: 2

Related Questions