我有一个使用 TestContainers 的抽象类 BaseIntegrationTest。问题是当我尝试运行像 UserRepositoryIntSpec 这样的简单数据库测试时,我遇到了一个异常,这意味着计数从 114 开始,而不是像预期的那样从 1 开始。为什么索引不是从 1 开始?为什么每次执行设置时我的本地数据库用户表都很清楚,因为我希望测试在容器中使用容器数据库运行,所以只会清除容器表。这绝对应该是我刚刚错过或不理解的简单事情。我将不胜感激。
对于迁移,我使用 Flyway 来测试 Spock。
不满足条件:
user1.getId() == 1 && user1.getRiskcustomerid() == 1 && user1.getDateCreated() != null
| | | | |
| 114 | false false
| false
基础集成测试
@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
}
应用程序.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