How to use TemporaryFolder class of org.junit.rules package

Best junit code snippet using org.junit.rules.TemporaryFolder

Run junit automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package org.junit;
2
3import java.lang.annotation.ElementType;
4import java.lang.annotation.Retention;
5import java.lang.annotation.RetentionPolicy;
6import java.lang.annotation.Target;
7
8/**
9 * Annotates fields that reference rules or methods that return a rule. A field must be public, not
10 * static, and a subtype of {@link org.junit.rules.TestRule} (preferred) or
11 * {@link org.junit.rules.MethodRule}. A method must be public, not static,
12 * and must return a subtype of {@link org.junit.rules.TestRule} (preferred) or
13 * {@link org.junit.rules.MethodRule}.
14 * <p>
15 * The {@link org.junit.runners.model.Statement} passed
16 * to the {@link org.junit.rules.TestRule} will run any {@link Before} methods,
17 * then the {@link Test} method, and finally any {@link After} methods,
18 * throwing an exception if any of these fail.  If there are multiple
19 * annotated {@link Rule}s on a class, they will be applied in order of methods first, then fields.
20 * However, if there are multiple fields (or methods) they will be applied in an order
21 * that depends on your JVM's implementation of the reflection API, which is
22 * undefined, in general. Rules defined by fields will always be applied
23 * after Rules defined by methods, i.e. the Statements returned by the former will
24 * be executed around those returned by the latter.
25 *
26 * <h3>Usage</h3>
27 * <p>
28 * For example, here is a test class that creates a temporary folder before
29 * each test method, and deletes it after each:
30 * <pre>
31 * public static class HasTempFolder {
32 *     &#064;Rule
33 *     public TemporaryFolder folder= new TemporaryFolder();
34 *
35 *     &#064;Test
36 *     public void testUsingTempFolder() throws IOException {
37 *         File createdFile= folder.newFile(&quot;myfile.txt&quot;);
38 *         File createdFolder= folder.newFolder(&quot;subfolder&quot;);
39 *         // ...
40 *     }
41 * }
42 * </pre>
43 * <p>
44 * And the same using a method.
45 * <pre>
46 * public static class HasTempFolder {
47 *     private TemporaryFolder folder= new TemporaryFolder();
48 *
49 *     &#064;Rule
50 *     public TemporaryFolder getFolder() {
51 *         return folder;
52 *     }
53 *
54 *     &#064;Test
55 *     public void testUsingTempFolder() throws IOException {
56 *         File createdFile= folder.newFile(&quot;myfile.txt&quot;);
57 *         File createdFolder= folder.newFolder(&quot;subfolder&quot;);
58 *         // ...
59 *     }
60 * }
61 * </pre>
62 * <p>
63 * For more information and more examples, see
64 * {@link org.junit.rules.TestRule}.
65 *
66 * <h3>Ordering</h3>
67 * <p>
68 * You can use {@link #order()} if you want to have control over the order in
69 * which the Rules are applied.
70 *
71 * <pre>
72 * public class ThreeRules {
73 *     &#064;Rule(order = 0)
74 *     public LoggingRule outer = new LoggingRule("outer rule");
75 *
76 *     &#064;Rule(order = 1)
77 *     public LoggingRule middle = new LoggingRule("middle rule");
78 *
79 *     &#064;Rule(order = 2)
80 *     public LoggingRule inner = new LoggingRule("inner rule");
81 *
82 *     // ...
83 * }
84 * </pre>
85 *
86 * @since 4.7
87 */
88@Retention(RetentionPolicy.RUNTIME)
89@Target({ElementType.FIELD, ElementType.METHOD})
90public @interface Rule {
91
92    int DEFAULT_ORDER = -1;
93
94    /**
95     * Specifies the order in which rules are applied. The rules with a higher value are inner.
96     *
97     * @since 4.13
98     */
99    int order() default DEFAULT_ORDER;
100
101}
102
Full Screen
copy
1package com.github.testframework.junit4;
2
3import com.google.common.base.Stopwatch;
4import lombok.extern.slf4j.Slf4j;
5import org.apache.commons.io.FileUtils;
6import org.junit.Rule;
7import org.junit.Test;
8import org.junit.rules.ExpectedException;
9import org.junit.rules.MethodRule;
10import org.junit.rules.RuleChain;
11import org.junit.rules.TemporaryFolder;
12import org.junit.rules.TestName;
13import org.junit.rules.TestRule;
14import org.junit.rules.Timeout;
15import org.junit.runner.Description;
16import org.junit.runner.RunWith;
17import org.junit.runners.model.FrameworkMethod;
18import org.junit.runners.model.Statement;
19import org.springframework.boot.test.context.SpringBootTest;
20import org.springframework.test.context.junit4.SpringRunner;
21
22import java.io.File;
23import java.util.concurrent.TimeUnit;
24
25/**
26 * JunitRuleTest
27 *
28 * @author dongdaiming(董代明)
29 * @date 2019-07-22
30 * @see <a href="https://blog.csdn.net/kingmax54212008/article/details/89003076">Junit Rule的使用</a>
31 */
32@Slf4j
33@RunWith(SpringRunner.class)
34@SpringBootTest
35public class JunitRuleTest {
36
37    // TemporaryFolder可用于在测试时生成文件并在测试完后自动删除
38    @Rule
39    public TemporaryFolder temporaryFolder = new TemporaryFolder(new File("/temp/junit"));
40
41    // TestName可以获取到当前测试方法的名称
42    @Rule
43    public TestName testName = new TestName();
44
45    // Timeout可以设置全局的超时时间
46    @Rule
47    public Timeout timeout = Timeout.seconds(15);
48
49    // 自定义方法规则-打印测试方法名与耗时
50    @Rule
51    public MethodLoggingRule methodLogger = new MethodLoggingRule();
52
53    // ExpectedException可以匹配异常类型和异常message
54    @Rule
55    public ExpectedException expectedException = ExpectedException.none();
56
57    @Rule
58    public RuleChain ruleChain = RuleChain.outerRule(new LoggingRule(3)).around(new LoggingRule(2)).around(new LoggingRule(1));
59
60    @Test
61    public void testTemporaryFolder() throws Exception {
62        File file = temporaryFolder.newFile();
63        log.info("file: {}", file.getAbsolutePath());
64        FileUtils.writeStringToFile(file, "abc", "utf-8", true);
65        log.info("read data: {}", FileUtils.readFileToString(file, "utf-8"));
66        TimeUnit.SECONDS.sleep(10);
67    }
68
69    @Test
70    public void testTimeout() throws InterruptedException {
71        TimeUnit.SECONDS.sleep(20);
72    }
73
74    @Test
75    public void testNotTimeout() throws InterruptedException {
76        TimeUnit.SECONDS.sleep(1);
77    }
78
79    @Test
80    public void testMethodLogRule() throws InterruptedException {
81        TimeUnit.MILLISECONDS.sleep(1234);
82    }
83
84    @Test
85    public void testExpectException1() {
86        expectedException.expect(NumberFormatException.class);
87        expectedException.expectMessage("For input string: \"a\"");
88        Integer.parseInt("a");
89    }
90
91    @Test(expected = ArithmeticException.class)
92    public void testExpectException2() {
93        int n = 1 / 0;
94    }
95
96    @Test
97    public void testRuleChain() {
98    }
99
100    @Slf4j
101    private static class MethodLoggingRule implements MethodRule {
102
103        @Override
104        public Statement apply(Statement base, FrameworkMethod method, Object target) {
105            String flag = target.getClass().getSimpleName() + "." + method.getName();
106            return new Statement() {
107                @Override
108                public void evaluate() throws Throwable {
109                    Stopwatch watch = Stopwatch.createStarted();
110                    base.evaluate();
111                    log.info("finished {}, duration: {} ms.", flag, watch.elapsed(TimeUnit.MILLISECONDS));
112                }
113            };
114        }
115    }
116
117    @Slf4j
118    private static class LoggingRule implements TestRule {
119
120        private int priority;
121
122        public LoggingRule(int priority) {
123            this.priority = priority;
124        }
125
126        @Override
127        public Statement apply(Statement base, Description description) {
128            return new Statement() {
129                @Override
130                public void evaluate() throws Throwable {
131                    log.info("starting LoggingRule-{}.", priority);
132                    base.evaluate();
133                    log.info("finished LoggingRule-{}", priority);
134                }
135            };
136        }
137    }
138}
139
Full Screen
copy
1public class org.junit.rules.TemporaryFolder$Builder {
2  protected org.junit.rules.TemporaryFolder$Builder();
3  public org.junit.rules.TemporaryFolder$Builder parentFolder(java.io.File);
4  public org.junit.rules.TemporaryFolder$Builder assureDeletion();
5  public org.junit.rules.TemporaryFolder build();
6  static java.io.File access$000(org.junit.rules.TemporaryFolder$Builder);
7  static boolean access$100(org.junit.rules.TemporaryFolder$Builder);
8}
9
Full Screen
copy
1File folder = File.createTempFile("testFileUtils", ""); // no suffix
2folder.delete();
3folder.mkdirs();
4folder.deleteOnExit();
5
Full Screen
copy
1try {
2    Path tmpDir = Files.createTempDirectory("tmpDir");
3    System.out.println(tmpDir.toString());
4    Files.delete(tmpDir);
5} catch (IOException e) {
6    e.printStackTrace();
7}
8
Full Screen
copy
1/**
2 * Creates a temporary subdirectory in the standard temporary directory.
3 * This will be automatically deleted upon exit.
4 * 
5 * @param prefix
6 *            the prefix used to create the directory, completed by a
7 *            current timestamp. Use for instance your application's name
8 * @return the directory
9 */
10public static File createTempDirectory(String prefix) {
11
12    final File tmp = new File(FileUtils.getTempDirectory().getAbsolutePath()
13            + "/" + prefix + System.currentTimeMillis());
14    tmp.mkdir();
15    Runtime.getRuntime().addShutdownHook(new Thread() {
16
17        @Override
18        public void run() {
19
20            try {
21                FileUtils.deleteDirectory(tmp);
22            } catch (IOException e) {
23                e.printStackTrace();
24            }
25        }
26    });
27    return tmp;
28
29}
30
Full Screen
copy
1public static final String tempDir = System.getProperty("java.io.tmpdir")+"tmp"+System.nanoTime();
2static {
3    File f = new File(tempDir);
4    if(!f.exists())
5        f.mkdir();
6}
7
Full Screen
copy
1Runtime.getRuntime().addShutdownHook(new Thread() {
2        @Override
3        public void run() {
4            //stackless deletion
5            String root = MainWindow.tempDir;
6            Stack<String> dirStack = new Stack<String>();
7            dirStack.push(root);
8            while(!dirStack.empty()) {
9                String dir = dirStack.pop();
10                File f = new File(dir);
11                if(f.listFiles().length==0)
12                    f.delete();
13                else {
14                    dirStack.push(dir);
15                    for(File ff: f.listFiles()) {
16                        if(ff.isFile())
17                            ff.delete();
18                        else if(ff.isDirectory())
19                            dirStack.push(ff.getPath());
20                    }
21                }
22            }
23        }
24    });
25
Full Screen
copy
1  /** Maximum loop count when creating temp directories. */
2  private static final int TEMP_DIR_ATTEMPTS = 10000;
3
4  /**
5   * Atomically creates a new directory somewhere beneath the system's temporary directory (as
6   * defined by the {@code java.io.tmpdir} system property), and returns its name.
7   *
8   * <p>Use this method instead of {@link File#createTempFile(String, String)} when you wish to
9   * create a directory, not a regular file. A common pitfall is to call {@code createTempFile},
10   * delete the file and create a directory in its place, but this leads a race condition which can
11   * be exploited to create security vulnerabilities, especially when executable files are to be
12   * written into the directory.
13   *
14   * <p>This method assumes that the temporary volume is writable, has free inodes and free blocks,
15   * and that it will not be called thousands of times per second.
16   *
17   * @return the newly-created directory
18   * @throws IllegalStateException if the directory could not be created
19   */
20  public static File createTempDir() {
21    File baseDir = new File(System.getProperty("java.io.tmpdir"));
22    String baseName = System.currentTimeMillis() + "-";
23
24    for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
25      File tempDir = new File(baseDir, baseName + counter);
26      if (tempDir.mkdir()) {
27        return tempDir;
28      }
29    }
30    throw new IllegalStateException(
31        "Failed to create directory within "
32            + TEMP_DIR_ATTEMPTS
33            + " attempts (tried "
34            + baseName
35            + "0 to "
36            + baseName
37            + (TEMP_DIR_ATTEMPTS - 1)
38            + ')');
39  }
40
Full Screen
copy
1public static File createTempDir() {
2    final String baseTempPath = System.getProperty("java.io.tmpdir");
3
4    Random rand = new Random();
5    int randomInt = 1 + rand.nextInt();
6
7    File tempDir = new File(baseTempPath + File.separator + "tempDir" + randomInt);
8    if (tempDir.exists() == false) {
9        tempDir.mkdir();
10    }
11
12    tempDir.deleteOnExit();
13
14    return tempDir;
15}
16
Full Screen
copy
1/**
2 * Create a new temporary directory. Use something like
3 * {@link #recursiveDelete(File)} to clean this directory up since it isn't
4 * deleted automatically
5 * @return  the new directory
6 * @throws IOException if there is an error creating the temporary directory
7 */
8public static File createTempDir() throws IOException
9{
10    final File sysTempDir = new File(System.getProperty("java.io.tmpdir"));
11    File newTempDir;
12    final int maxAttempts = 9;
13    int attemptCount = 0;
14    do
15    {
16        attemptCount++;
17        if(attemptCount > maxAttempts)
18        {
19            throw new IOException(
20                    "The highly improbable has occurred! Failed to " +
21                    "create a unique temporary directory after " +
22                    maxAttempts + " attempts.");
23        }
24        String dirName = UUID.randomUUID().toString();
25        newTempDir = new File(sysTempDir, dirName);
26    } while(newTempDir.exists());
27
28    if(newTempDir.mkdirs())
29    {
30        return newTempDir;
31    }
32    else
33    {
34        throw new IOException(
35                "Failed to create temp dir named " +
36                newTempDir.getAbsolutePath());
37    }
38}
39
40/**
41 * Recursively delete file or directory
42 * @param fileOrDir
43 *          the file or dir to delete
44 * @return
45 *          true iff all files are successfully deleted
46 */
47public static boolean recursiveDelete(File fileOrDir)
48{
49    if(fileOrDir.isDirectory())
50    {
51        // recursively delete contents
52        for(File innerFile: fileOrDir.listFiles())
53        {
54            if(!FileUtilities.recursiveDelete(innerFile))
55            {
56                return false;
57            }
58        }
59    }
60
61    return fileOrDir.delete();
62}
63
Full Screen
copy
1public static File createTempDir() {
2  File baseDir = new File(System.getProperty("java.io.tmpdir"));
3  String baseName = System.currentTimeMillis() + "-";
4
5  for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
6    File tempDir = new File(baseDir, baseName + counter);
7    if (tempDir.mkdir()) {
8      return tempDir;
9    }
10  }
11  throw new IllegalStateException("Failed to create directory within "
12      + TEMP_DIR_ATTEMPTS + " attempts (tried "
13      + baseName + "0 to " + baseName + (TEMP_DIR_ATTEMPTS - 1) + ')');
14}
15
Full Screen
copy
1private static final int TEMP_DIR_ATTEMPTS = 10000;
2
Full Screen
copy
1public static Path createTempDirectory(Path dir,
2                       String prefix,
3                       FileAttribute<?>... attrs)
4                                throws IOException
5
Full Screen
copy
1@Rule
2public TemporaryFolder folder = new TemporaryFolder();
3
Full Screen
copy
1@Test
2@ExtendWith(TempDirectory.class)
3void test(@TempDir Path tempDir) {
4    Path file = tempDir.resolve("test.txt");
5    writeFile(file);
6    assertExpectedFileContent(file);
7}
8
Full Screen
copy
1dependencies {
2    testImplementation 'org.junit-pioneer:junit-pioneer:0.1.2'
3}
4
Full Screen
copy
1<dependency>
2   <groupId>org.junit-pioneer</groupId>
3   <artifactId>junit-pioneer</artifactId>
4   <version>0.1.2</version>
5   <scope>test</scope>
6</dependency>
7
Full Screen
copy
1@Test
2void writeItemsToFile(@TempDir Path tempDir) throws IOException {
3    Path file = tempDir.resolve("test.txt");
4
5    new ListWriter(file).write("a", "b", "c");
6
7    assertEquals(singletonList("a,b,c"), Files.readAllLines(file));
8}
9
Full Screen
copy
1File myTempDir = Files.createTempDir();
2
Full Screen
copy
1Path tempDirWithPrefix = Files.createTempDirectory(prefix);
2
Full Screen
copy
1public static File createTempDirectory()
2    throws IOException
3{
4    final File temp;
5
6    temp = File.createTempFile("temp", Long.toString(System.nanoTime()));
7
8    if(!(temp.delete()))
9    {
10        throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());
11    }
12
13    if(!(temp.mkdir()))
14    {
15        throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());
16    }
17
18    return (temp);
19}
20
Full Screen
copy
1File tmpFile = ...
2try {
3   // deal with tempFile
4} finally {
5    tempFile.delete();
6}
7
Full Screen
copy
1public class MyTestCase {
2    private File tmpFile = null;
3
4    @Before
5    public void setUp() {
6        tmpFile = ...;
7    }
8
9    @Test
10    public void setUp() {
11        // deal with tmpFile
12    }
13
14    @After
15    public void setUp() {
16        tmpFile.delete();
17    }
18}
19
Full Screen
copy
1<plugin>
2    <groupId>org.apache.maven.plugins</groupId>
3    <artifactId>maven-surefire-plugin</artifactId>
4    <version>2.6</version>
5    <configuration>
6        <systemPropertyVariables>
7            <myOutDir>${project.build.outputDirectory}</myOutDir>
8        </systemPropertyVariables>
9    </configuration>
10</plugin>
11
Full Screen
copy
1File file = File.createTempFile( "some-prefix", "some-ext");
2file.deleteOnExit();
3
Full Screen
copy
1File file = File.createTempFile( "prefix", "ext", new File("/some/dir/path"));
2
Full Screen
copy
1<plugins>
2    [...]
3      <plugin>
4        <groupId>org.apache.maven.plugins</groupId>
5        <artifactId>maven-surefire-plugin</artifactId>
6        <version>2.12.3</version>
7        <configuration>
8          <workingDirectory>${project.build.directory}</workingDirectory>
9        </configuration>
10      </plugin>
11    [...]
12</plugins>
13
Full Screen
copy
1public class TestApp {
2    @Rule
3    public Timeout globalTimeout = new Timeout(20, TimeUnit.MILLISECONDS);
4
5    ......
6    ......
7
8 }
9
Full Screen
copy
1public class TempFolderTest {
2
3 @Rule
4 public TemporaryFolder tempFolder= new TemporaryFolder();
5
6 @Test
7 public void testTempFolder() throws IOException {
8  File folder = tempFolder.newFolder("demos");
9  File file = tempFolder.newFile("Hello.txt");
10
11  assertEquals(folder.getName(), "demos");
12  assertEquals(file.getName(), "Hello.txt");
13
14 }
15
16
17}
18
Full Screen
copy
1public class JunitRuleTest {
2
3  @Rule
4  public TemporaryFolder tempFolder = new TemporaryFolder();
5
6  @Test
7  public void testRule() throws IOException {
8    File newFolder = tempFolder.newFolder("Temp Folder");
9    assertTrue(newFolder.exists());
10  }
11} 
12
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used methods in TemporaryFolder

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)