通过命中SpringBootApplication类

时间:2017-04-02 15:46:45

标签: java spring spring-boot spring-boot-test

我有一个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 Tests
@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课程?

谢谢!

1 个答案:

答案 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) {
            // ...
        }
    }
}

当我写完这个答案时,我注意到了一些事情:

无论如何,祝你好运!