How does Junit @Rule work?

前端 未结 4 1482
予麋鹿
予麋鹿 2020-11-28 18:40

I want to write test cases for a bulk of code, I would like to know details of JUnit @Rule annotation feature, so that I can use it for writing test cases. Ple

4条回答
  •  情书的邮戳
    2020-11-28 19:21

    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:

    • http://www.codeaffine.com/2012/09/24/junit-rules/

提交回复
热议问题