Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit Rule TemporaryFolder

I'm creating a TemporaryFolder using the @Rule annotation in JUnit 4.7. I've tried to create a new folder that is a child of the temp folder using tempFolder.newFolder("someFolder") in the @Before (setup) method of my test. It seems as though the temporary folder gets initialized after the setup method runs, meaning I can't use the temporary folder in the setup method. Is this correct (and predictable) behavior?

like image 411
Jeff Storey Avatar asked Apr 27 '10 15:04

Jeff Storey


People also ask

How do I use temp folder in JUnit?

Example of usage: public static class HasTempFolder { @Rule public TemporaryFolder folder= new TemporaryFolder(); @Test public void testUsingTempFolder() throws IOException { File createdFile= folder. newFile("myfile. txt"); File createdFolder= folder.

What is JUnit test rule?

A JUnit rule is defined as a component that is used to obstruct the test method calls and allows us to perform something before and after the test method is invoked. The JUnit provides the following rules to: Create directories/files that are deleted after a test method has been run.

How do you create a rule in JUnit?

To write a custom rule, we need to implement the TestRule interface. As we can see, the TestRule interface contains one method called apply(Statement, Description) that we must override to return an instance of Statement. The statement represents our tests within the JUnit runtime.

What is @ClassRule annotation in JUnit?

Annotation Type ClassRule. @Retention(value=RUNTIME) @Target(value={FIELD,METHOD}) public @interface ClassRule. Annotates static fields that reference rules or methods that return them. A field must be public, static, and a subtype of TestRule . A method must be public static, and return a subtype of TestRule .


1 Answers

This is a problem in Junit 4.7. If you upgrade a newer Junit (for example 4.8.1) all @Rule will have been run when you enter the @Before method:s. A related bug report is this: https://github.com/junit-team/junit4/issues/79

like image 71
Lennart Schedin Avatar answered Sep 22 '22 10:09

Lennart Schedin