@BeforeClass and inheritance - order of execution

前端 未结 16 2087
梦如初夏
梦如初夏 2020-12-02 11:39

I have an abstract base class, which I use as a base for my unit tests (TestNG 5.10). In this class, I initialize the whole environment for my tests, setting up database map

16条回答
  •  生来不讨喜
    2020-12-02 12:17

    I've faced a similar issue today, the only difference was a Base class was not abstract

    Here's my case

    public class A {
        @BeforeClass
        private void doInitialization() {...}
    }
    
    public class B extends A {
        @BeforeClass
        private void doSpecificInitialization() {...}
    
        @Test
        public void doTests() {...}
    }
    

    It occurred that a @BeforeClass method from class A was never executed.

    • A.doInitialization() -> THIS WAS NEVER EXECUTED silently
    • B.doSpecificInitialization()
    • B.doTests()

    Playing with privacy modifiers I found that TestNG will not execute a @BeforeClass annotated method from inherited class if a method is not visible from a class-inheritor

    So this will work:

    public class A {
        @BeforeClass
        private void doInitialization() {...}
    }
    
    public class B extends A {
        @BeforeClass
        //Here a privacy modifier matters -> please make sure your method is public or protected so it will be visible for ancestors
        protected void doSpecificInitialization() {...}
    
        @Test
        public void doTests() {...}
    }
    

    As a result following happens:

    • A.doInitialization()
    • B.doSpecificInitialization()
    • B.doTests()

提交回复
热议问题