How to autowire field in static @BeforeClass?

后端 未结 5 1260
天命终不由人
天命终不由人 2021-01-31 07:56
@RunWith(SpringJUnit4ClassRunner.class)
public void ITest {
    @Autowired
    private EntityRepository dao;

    @BeforeClass
    public static void init() {
        da         


        
5条回答
  •  一个人的身影
    2021-01-31 08:52

    UPD for Spring 2.x versions.

    Spring 2.x supports new feature a SpringExtension for Junit 5 Jupiter, where all you have to do is:

    1. Declare your test class with @ExtendWith(SpringExtension.class)

    2. Inject your @BeforeAll (replacement for @BeforeClass in JUnit 5) with the bean

    For example:

    @ExtendWith(SpringExtension.class)
    ...
    public void ITest {
    
        @BeforeAll
        public static void init(@Autowired EntityRepository dao) {
            dao.save(initialEntity);
        }
    
    }
    

    Assuming you correctly configured JUnit 5 Jupiter with Spring 2.x

    More about it here: https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#testcontext-junit-jupiter-extension

提交回复
热议问题