How to autowire field in static @BeforeClass?

后端 未结 5 1259
天命终不由人
天命终不由人 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:42

    It looks to me that you are trying to populate DB before tests.

    I would give a try to two options:

    • If you can extract initial scripts to sql file (if that is option for you without using repository bean) you can use this approach and annotate your test with @Sql
    • You can explore DbUnit and here is link to spring dbunit connector which is doing exactly that and helping you populate DB before tests. Here is a github link for integrating between spring test framework and dbunit. After you do that you have @DatabaseSetup and @DatabaseTearDown which will do thing on DB you need

    I know that this does not answer how to inject bean in static @BeforeClass but form code it looks it is solving your problem.

    Update: I recently run into same problem in my project and dug out this article which helped me and I think it is elegant way of dealing with this type of problem. You can extend SpringJUnit4ClassRunner with listener which can do instance level setup with all your defined beans.

提交回复
热议问题