我正在对几个弹簧组件进行单元测试,主要的测试是一个由Spring自动运行的ApplicationRunner
。
但是,在调用此ApplicationRunner
bean之前,我必须运行一段代码。
=>我该怎么做?
我尝试使用@Before
和@PostConstruct
,但都在AppllicationRunner之后被调用。
我不能分享实际的代码,但这是原理:
@RunWith(SpringRunner.class)
// The class to be tested
// Comes with many bean, the main one being an ApplicationRunner
@SpringBootTest(classes = { MyApplication.class })
public class MyApplicationTest {
@Autowired private SomeProperties someProperties;
// the method I need to run before the ApplicationRunner
@PostConstruct // also tried @Before
public void clean() throws IOException {
// need to be sure some output dir is empty before starting
cleanOutputDirectory(someProperties);
}
@Test
public void testApplication() throws InterruptedException {
// test the ApplicationRunner has written some files
// in the output directory
}
}
最佳答案
您可以使用ApplicationRunner
在测试中定义一个新的@Order(Ordered.HIGHEST_PRECEDENCE)
bean。