Prev Next

Testing / Junit Interview questions III

Junit: What is @Rule annotation?

@Rule annotation in Junit is used to create objects that later can be used with the test methods.

Junit @Rule annotation works on the principle of AOP (aspect oriented programming). It intercepts the test method thus providing an opportunity perform some action before or after the execution of a particular test method.

public class JunitRuleExampleTest {

  @Rule
  public TemporaryFolder tFolder = new TemporaryFolder();

  @Test
  public void testRule() throws IOException {
    File txtFile = tFolder.newFile("sample.txt");
    assertTrue(txtFile.exists());
  }
} 

Every time the above test method is executed, a temporary folder is created and used in the test while executing and be deleted/garbage collected after the test run.

More Related questions...

Show more question and Answers...


Comments & Discussions