Nifty JUnit : Using Rule on Method and Class level
As shown in a the post Nifty JUnit : Working with temporary files, it is possible to use @Rule
in a JUnit test, which is a Method level Rule. In this example I would like to show the variation of the @ClassRule
for a Class level Rule.
Method Rule
The @Rule
is fired before each test method (just like @Before
) and after each test method (just like @After
) of the test class, as shown in the example below.
JUnitRuleTest
package com.jdriven; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; public class JUnitRuleTest { //The Folder will be created before each test method and (recursively) deleted after each test method. @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Test public void testJUnitRule() throws IOException { File tempFile = temporaryFolder.newFile("tempFile.txt"); //Your test should go here. } }
Class Rule
Besides the regular @Rule
we have the possibility to create a @ClassRule
. In the example of the TemporaryFolder it will result in a folder which is created before all test methods (just like @BeforeClass
) and destroyed after all test methods (just like @AfterClass
). In the example below you can create a temporary file and use the exact same file in all the test methods. The temporary file will be deleted when all the test methods are finished.
JUnitClassRuleTest
package com.jdriven; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; public class JUnitClassRuleTest { //The Folder will be (recursively) deleted after all test. @ClassRule public static TemporaryFolder temporaryFolder = new TemporaryFolder(); public static File tempFile; @BeforeClass public static void createTempFile() throws IOException { tempFile = temporaryFolder.newFile("tempFile.txt"); //The tempFile will be deleted when the temporaryFolder is deleted. } @Test public void testJUnitClassRule_One() { //Your test should go here, which uses tempFile } @Test public void testJUnitClassRule_Two() { //Your test should go here and uses the same tempFile } }
Reference: | Nifty JUnit : Using Rule on Method and Class level from our JCG partner Willem Cheizoo at the JDriven blog. |