Junit Rules work on the principle of AOP (aspect oriented programming). It intercepts the test method thus providing an opportunity to do some stuff before or after the execution of a particular test method.
Take the example of the below code:
public class JunitRuleTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Test
public void testRule() throws IOException {
File newFolder = tempFolder.newFolder("Temp Folder");
assertTrue(newFolder.exists());
}
}
Every time the above test method is executed, a temporary folder is created and it gets deleted after the execution of the method. This is an example of an out-of-box rule provided by Junit.
Similar behaviour can also be achieved by creating our own rules. Junit provides the TestRule interface, which can be implemented to create our own Junit Rule.
Here is a useful link for reference: