How does Junit @Rule work?

前端 未结 4 1480
予麋鹿
予麋鹿 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:09

    Rules are used to enhance the behaviour of each test method in a generic way. Junit rule intercept the test method and allows us to do something before a test method starts execution and after a test method has been executed.

    For example, Using @Timeout rule we can set the timeout for all the tests.

    public class TestApp {
        @Rule
        public Timeout globalTimeout = new Timeout(20, TimeUnit.MILLISECONDS);
    
        ......
        ......
    
     }
    

    @TemporaryFolder rule is used to create temporary folders, files. Every time the test method is executed, a temporary folder is created and it gets deleted after the execution of the method.

    public class TempFolderTest {
    
     @Rule
     public TemporaryFolder tempFolder= new TemporaryFolder();
    
     @Test
     public void testTempFolder() throws IOException {
      File folder = tempFolder.newFolder("demos");
      File file = tempFolder.newFile("Hello.txt");
    
      assertEquals(folder.getName(), "demos");
      assertEquals(file.getName(), "Hello.txt");
    
     }
    
    
    }
    

    You can see examples of some in-built rules provided by junit at this link.

提交回复
热议问题