开发者

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

开发者 https://www.devze.com 2023-03-19 07:23 出处:网络
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 a

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?


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


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号