2

我有一个 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类的情况下运行?

谢谢!

4

1 回答 1

2

根据要求,这是使用弹簧属性的尝试(没有方便的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) {
            // ...
        }
    }
}

当我写下这个答案时,我注意到了几件事:

无论如何,祝你好运!

于 2017-04-03T22:51:03.040 回答