Junit before class ( non static )

后端 未结 8 644
旧巷少年郎
旧巷少年郎 2020-12-02 12:12

Are there any best practices to get Junit execute a function once in a test file , and it should also not be static.

like @BeforeClass on non static fun

8条回答
  •  攒了一身酷
    2020-12-02 12:22

    To use an empty constructor is the easiest solution. You can still override the constructor in the extended class.

    But it's not optimal with all the inheritance. That's why JUnit 4 uses annotations instead.

    Another option is to create a helper method in a factory/util class and let that method do the work.

    If you're using Spring, you should consider using the @TestExecutionListeners annotation. Something like this test:

    @RunWith(SpringJUnit4ClassRunner.class)
    @TestExecutionListeners({CustomTestExecutionListener.class, 
         DependencyInjectionTestExecutionListener.class})
    @ContextConfiguration("test-config.xml")
    public class DemoTest {
    

    Spring's AbstractTestExecutionListener contains for example this empty method that you can override:

    public void beforeTestClass(TestContext testContext) throws Exception {
        /* no-op */
    }
    

    NOTE: DO NOT overlook/miss DependencyInjectionTestExecutionListener while adding custom TestExecutionListeners. If you do, all the autowires will be null.

提交回复
热议问题