【发布时间】:2017-04-02 15:46:44
【问题描述】:
我有一个 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 这个基类的 Spring Boot 测试:
@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 类有吗?
谢谢!
【问题讨论】:
-
您是否尝试过使用 Spring 配置文件和配置注释?例如,您可以使用
@Profile("application")注释SpringBootApp类。然后将您的@Before和@After注释和方法抽象到一个TestConfig类中,该类用@Configuration和@Profile("test").注释,最后在您的BaseTest类(或其他测试类)中,您可以用@ 注释它987654342@。这应该会阻止您的SpringBootApp类被初始化。这样的事情有用吗? -
我可能会通过 spring 属性管理
workOffline,然后使用SpringBootTest#properties将属性设置为 false -
@ninj 很有趣!您能否举例说明如何使用 SprinbBoot 将变量设置为特定值?谢谢
-
我的问题本质上是想以某种方式对@SpringBootApplication 说我现在正在实际运行测试,这不是实际的应用程序.. 有没有办法做到这一点?
标签: java spring spring-boot spring-boot-test