我有一个使用TestContainers的抽象类BaseIntegrationTest。问题是当我尝试运行像UserRepositoryIntSpec这样的简单数据库测试时,我遇到了一个异常,这意味着计数从114开始,而不是预期的1。为什么索引不是从1开始?为什么每次执行安装程序时都会清除我的本地db用户表,因为我希望测试将在具有容器db使用情况的容器中运行,因此仅会清除容器表。 绝对应该是我只是想念或不理解的简单事情。感谢您的帮助。
对于迁移,我使用Flyway,用于测试Spock。
条件不满足:
user1.getId() == 1 && user1.getRiskcustomerid() == 1 && user1.getDateCreated() != null
| | | | |
| 114 | false false
| false
BaseIntegrationTest
@ContextConfiguration
@SpringBootTest(webEnvironment = DEFINED_PORT)
@Testcontainers
@Slf4j
abstract class BaseIntegrationTest extends Specification {
protected static PostgreSQLContainer postgres = new PostgreSQLContainer()
.withDatabaseName("db")
.withUsername("root")
.withPassword("root")
def setupSpec() {
startPostgresIfNeeded()
['spring.datasource.url' : postgres.getJdbcUrl(),
'spring.datasource.username': postgres.getUsername(),
'spring.datasource.password': postgres.getPassword()
].each { k, v ->
System.setProperty(k, v)
}
}
private static void startPostgresIfNeeded() {
if (!postgres.isRunning()) {
log.info("[BASE-INTEGRATION-TEST] - Postgres is not started. Running...")
postgres.start()
}
}
def cleanupSpec() {
if (postgres.isRunning()) {
log.info("[BASE-INTEGRATION-TEST] - Stopping Postgres...")
postgres.stop()
}
}
}
UserRepositoryIntSpec
class UserRepositoryIntSpec extends BaseIntegrationTest {
@Autowired
private UserRepository UserRepository
def setup() {
UserRepository.deleteAll()
}
def "FindAll returns all users correctly"() {
given:
List<Integer> friends = [1,2]
User User1 = User.builder()
.riskcustomerid(1)
.possibleids([1000, 1001])
.preferableid(1000)
.totalfriendscount(2)
.friends(friends)
.build()
User User2 = User.builder()
.riskcustomerid(2)
.possibleids([8000, 8001])
.preferableid(8000)
.totalfriendscount(3)
.friends(friends)
.build()
when:
UserRepository.saveAll([User1, User2])
then:
List<User> Users = UserRepository.findAll()
assert Users.size() == 2
User user1 = Users.get(0)
User user2 = Users.get(1)
assert user1.getId() == 1 && user1.getRiskcustomerid() == 1 && user1.getDateCreated() != null
assert user2.getId() == 2 && user2.getRiskcustomerid() == 2 && user2.getDateCreated() != null
}
Application.yml
spring:
datasource:
url: jdbc:postgresql://localhost:5432/db
username: root
password: root
hikari:
connection-timeout: 10000
leak-detection-threshold: 60000
validation-timeout: 30000
connection-test-query: SELECT 1;
jdbc-url: jdbc:postgresql://localhost:5432/db
username: root
password: root
data-source-properties: stringtype=unspecified
maximum-pool-size: 16
max-lifetime: 1800000
transaction-isolation: TRANSACTION_READ_COMMITTED
pool-name: hikari.local
driver-class-name: org.postgresql.Driver
jpa:
hibernate:
ddl-auto: update
flyway:
schemas: schema1
baseline-on-migrate: false
server:
port: 8080
答案 0 :(得分:4)
我看到您正在使用url: jdbc:postgresql://localhost:5432/db
。您的意思是说“请针对我的本地数据库运行”:)
对于您的用例,建议在Testcontainers中使用JDBC-based containers。它将自动启动容器,并在您关闭与容器的最后一个连接时销毁它。