我有一个SpringBootApplication类,它有一个@PostConstruct
方法(它初始化数据库连接的类型):
@SpringBootApplication
public class SpringBootApp extends WebMvcConfigurerAdapter {
public static boolean workOffline = false;
private boolean setupSchema = false;
private IGraphService graphService;
private DbC conf;
@Autowired
public SpringBootApp(IGraphService graphService, DbC conf)
{
this.graphService = graphService;
this.conf = conf;
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootApp.class, args);
}
@PostConstruct
public void initializeDB() {
if (workOffline) {
conf.setupOfflineEnvironment();
return;
}
else {
conf.setupProdEnvironment();
}
if (setupSchema) {
graphService.setupTestUsers();
}
}
}
我也在使用extend
这个基类:
@RunWith(SpringRunner.class)
@Ignore
@SpringBootTest
public class BaseTest {
@Before
public void beforeTest() {
if (SpringBootApp.workOffline) {
conf.setupOfflineEnvironment();
} else {
conf.setupTestEnvironment();
}
graphService.setupTestUsers();}
@After
public void afterTest() {
graphService.deleteAllData();
}
}
我的测试位于tests/
下,而我的源代码位于src/
不幸的是,有些情况beforeTest()
将在@PostConstuct
之前执行,并且有些情况会在执行之后执行..有没有办法让我的测试运行@SprinbBootTest
而无需输入/建设SpringBootApp
课程?
谢谢!
答案 0 :(得分:1)
根据要求,这是尝试使用spring属性(没有IDE方便,所以请原谅任何错误)
您可以使用SpringBootTest#properties
为测试设置属性@RunWith(SpringRunner.class)
@Ignore
@SpringBootTest(properties="springBootApp.workOffline=true")
public class BaseTest {
@Before
public void beforeTest() { /* setup */ }
@After
public void afterTest() { /* teardown */ }
}
现在我们知道我们可以在测试中设置spring属性,我们可以设置应用程序来使用该属性:
@SpringBootApplication
public class SpringBootApp extends WebMvcConfigurerAdapter {
@Value("${springBootApp.workOffline:false}")
private boolean workOffline = false;
@Value("${springBootApp.setupSchema:false}")
private boolean setupSchema = false;
@PostConstruct
public void initializeDB() {
if (workOffline) {
// ...
} else {
// ...
}
if (setupSchema) {
// ...
}
}
}
当我写完这个答案时,我注意到了一些事情:
workOffline
以便可以运行测试,那么您可能只想将数据库设置操作移出应用程序并转移到BaseTest
类中。setupSchema
@Sql
和@SqlGroup
:https://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#__sql 无论如何,祝你好运!