java Spring试验:为org.springframework.test.context.jdbc.Sql配置数据源

2uluyalo  于 2023-03-21  发布在  Java
关注(0)|答案(1)|浏览(105)

在我的Sping Boot 项目中,我有两个数据源

@Primary
    @Bean(name = "pgDatasource")
    public BasicDataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(env.getProperty("spring.datasource.dbcp2.driver-class-name"));
        dataSource.setUrl(env.getProperty("spring.datasource.dbcp2.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.dbcp2.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.dbcp2.password"));
        dataSource.setMaxActive(Integer.valueOf(env.getProperty("spring.datasource.dbcp2.max-total")));
        dataSource.setMaxIdle(Integer.valueOf(env.getProperty("spring.datasource.dbcp2.max-idle")));
        dataSource.setInitialSize(Integer.valueOf(env.getProperty("spring.datasource.dbcp2.initial-size")));
        return dataSource;
    }

    @Bean(name = "h2Datasource")
    public BasicDataSource h2DataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(env.getProperty("spring.h2.datasource.driver-class-name"));
        dataSource.setUrl(env.getProperty("spring.h2.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.h2.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.h2.datasource.password"));

        Resource initData = new ClassPathResource("scripts/inmem.sql");
        DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initData);
        DatabasePopulatorUtils.execute(databasePopulator, dataSource);

        return dataSource;
    }

这里PostgreSQL的数据源是一个主bean。在我的几个测试中,我想对h2数据库运行一个脚本。为此,我尝试使用@Sql注解。但是,如果我使用@Sql,它会对pgDatasource运行脚本。我可以将h2配置为这些测试的主bean,但是测试方法的主体依赖于pgDatasource为主bean的配置。

供试品

@Test
@Sql(scripts = "/clean_login_attempts.sql", executionPhase = AFTER_TEST_METHOD)
void loginAttemptsIncrementTheCount() throws Exception {
    unsuccessfulLoginRequest();
    unsuccessfulLoginRequest();
    unsuccessfulLoginRequest();

    LoginAttempt loginAttempt = loginAttemptService.getAttempt("admin");
    assertEquals(3, loginAttempt.getAttempt());
}

是否可以为org.springframework.test.context.jdbc.Sql annotation配置数据源?

3wabscal

3wabscal1#

添加

config = @SqlConfig(dataSource = "h2Datasource", transactionManager = "h2tx")

解决了这个问题。

@Test
@Sql(scripts = "/clean_login_attempts.sql", executionPhase = AFTER_TEST_METHOD, config = @SqlConfig(dataSource = "h2Datasource", transactionManager = "h2tx"))
void loginAttemptsIncrementTheCount() throws Exception {
    unsuccessfulLoginRequest();
    unsuccessfulLoginRequest();
    unsuccessfulLoginRequest();

    LoginAttempt loginAttempt = loginAttemptService.getAttempt("admin");
    assertEquals(3, loginAttempt.getAttempt());
}

相关问题