Using Autowired in a TestExecutionListener class for BeforeClass junit

前端 未结 1 1261
粉色の甜心
粉色の甜心 2021-02-09 02:25

I need to do a @BeforeClass method in junit but inject values using Spring so can\'t switch private variables to static. I am trying to do

1条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-09 02:59

    It's not the cleanest, but it works:

    public class MyTestListener extends AbstractTestExecutionListener {
    
        @Value("${my.value}")
        private String myValue;
        @Autowired
        private MyBean myBean;
    
        @Override
        public void beforeTestClass(TestContext testContext) throws Exception {
            testContext.getApplicationContext()
                    .getAutowireCapableBeanFactory()
                    .autowireBean(this);
        }
    }
    

    0 讨论(0)
提交回复
热议问题