How to autowire field in static @BeforeClass?

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

    One workaround that I have been using to get this working is to use @Before with a flag to skip it being executed for each testcase

    @RunWith(SpringJUnit4ClassRunner.class)
    public class BaseTest {
    
    @Autowired
    private Service1 service1;
    
    @Autowired
    private Service2 service2;
    
    private static boolean dataLoaded = false;
    
    @Before
    public void setUp() throws Exception {
    
        if (!dataLoaded) {
            service1.something();
            service2.somethingElse();
            dataLoaded = true;
        }
      }
    }
    

提交回复
热议问题