gpt4 book ai didi

java - Spring 测试 : configure datasource for org. springframework.test.context.jdbc.Sql

转载 作者:行者123 更新时间:2023-12-03 23:14:30 25 4
gpt4 key购买 nike

在我的 Spring 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。

测试 sample :
@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 配置数据源注解?

最佳答案

添加 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());
}

关于java - Spring 测试 : configure datasource for org. springframework.test.context.jdbc.Sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53625526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com