PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 2, 2022

[FIXED] How to add files inside temporary directory in JUnit

 November 02, 2022     file, java, junit     No comments   

Issue

I found two ways to create temporary directories in JUnit.

Way 1:

@Rule
public TemporaryFolder tempDirectory = new TemporaryFolder();

@Test
public void testTempDirectory() throws Exception {
    tempDirectory.newFile("test.txt");
    tempDirectory.newFolder("myDirectory");
    // how do I add files to myDirectory?
}

Way 2:

@Test
public void testTempDirectory() throws Exception {
    File myFile = File.createTempFile("abc", "txt");
    File myDirectory = Files.createTempDir();
    // how do I add files to myDirectory?
}

As the comment above mentions, I have a requirement where I want to add some temporary files in these temporary directories. Run my test against this structure and finally delete everything on exit.

How do I do that?


Solution

You can do it the same way you do it for real folders.

@Rule
public TemporaryFolder rootFolder = new TemporaryFolder();

@Test
public void shouldCreateChildFile() throws Exception {
    File myFolder = rootFolder.newFolder("my-folder");

    File myFile = new File(myFolder, "my-file.txt");
}


Answered By - Sasha Shpota
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing