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?
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.
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.
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.
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With