JUnit: @Before only for some test methods?

前端 未结 6 1412
我寻月下人不归
我寻月下人不归 2020-12-30 18:29

I have some common set up code that I\'ve factored out to a method marked with @Before. However, it is not necessary for all this code to run for every single t

6条回答
  •  半阙折子戏
    2020-12-30 19:17

    @Nested + @ForEach

    Totally agree with the point of moving the related code to an inner class. So here what I have done.

    1. Create an inner class inside your test class
    2. Annotate the inner class with @Nested
    3. Move all the test methods you want to use in the inner class
    4. Write the init code inside the inner class and annotate it with @ForEach

    Here is the code:

    class Testing {
    
        @Test
        public void testextmethod1() {
        
          System.out.println("test ext method 1");
        
        }
        
        @Nested
        class TestNest{
        
           @BeforeEach
           public void init() {
              System.out.println("Init");
           }
        
           @Test
           public void testmethod1() {
              System.out.println("This is method 1");
           }
        
           @Test
           public void testmethod2() {
              System.out.println("This is method 2");
           }
        
           @Test
           public void testmethod3() {
              System.out.println("This is method 3");
           }
            
         }
    
         @Test
         public void testextmethod2() {
        
             System.out.println("test ext method 2");
        
         }
    
    }
    

    Here is the output

    test ext method 1
    test ext method 2
    Init
    This is method 1
    Init
    This is method 2
    Init
    This is method 3
    

    Note: I am not sure if this is supported in Junit4. I am doing this in JUnit5

提交回复
热议问题