Tuesday, 17 May 2016

TemporaryFolder in Junit

Dependencies:

    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>19.0</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

Code:
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.File;

public class TestTempFolder {

  // create temporary folder using Junit, it will be deleted automatically upon test success or failure
  // restriction: cannot be static
 // should be public
  @Rule
  public TemporaryFolder testFolder = new TemporaryFolder();

  @Test
  public void testTempFolder() throws Exception {
    // create file inside of temporary folder
    File mainFile = testFolder.newFile("main.csv");
    // write data into newly created file using guava lib
    Files.write("main data", mainFile, Charsets.UTF_8);
    // create folder inside of temporary folder
    File nestedFolder = testFolder.newFolder("nested");
    // create file inside of nested folder
    File nestedFile = new File(nestedFolder, "nested.csv");
    // write data into newly created file using guava lib
    Files.write("nested data", nestedFile, Charsets.UTF_8);
  }

}

No comments:

Post a Comment