您可以将迁移文件保留在 src 下,而无需将它们复制到您的测试文件夹中。运行@SpringBootTest 时,它们已不再使用。这也确保您使用所有 production 迁移进行我们的测试
此外,您不一定需要单独的属性文件进行测试。但你可以。
以下是使用 TestContainers 的 IntegrationTesting 示例,它使用 application.properties 以及 flyway 迁移,因为测试的行为就像您通常运行应用程序一样。
这是一个抽象类,它确保测试在整个 Spring 上下文中运行,因此Flyway 也参与其中。在初始化程序中,数据源配置属性被TestContainers 数据库中的属性覆盖。这样做你直接使用真实的application.properties 并模拟一点真实的;))
@ActiveProfiles("test")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@ContextConfiguration(initializers = AbstractPostgreSQLTestContainerIT.Initializer.class)
@Testcontainers
public abstract class AbstractPostgreSQLTestContainerIT {
private static final String POSTGRES_VERSION = "postgres:11.1";
public static PostgreSQLContainer database;
static {
database = new PostgreSQLContainer(POSTGRES_VERSION);
database.start();
}
static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(
configurableApplicationContext,
"spring.datasource.url=" + database.getJdbcUrl(),
"spring.datasource.username=" + database.getUsername(),
"spring.datasource.password=" + database.getPassword()
);
}
}
}
现在您可以定义几个测试类,如下所示:
class MyIntegrationTest extends AbstractPostgreSQLTestContainerIT { }
在此类中运行测试时,SpringBoot 应用程序启动并使用TestContainers 数据库。
出于我的目的,我还实现了一个简单的注释:
@TransactionalSQLTest("classpath:db/test/create_base_foo_data.sql")
void updateFooByExternalIdentifier_DTOProvided_ShouldReturnUpdatedFoo() {}
代码
/**
* Annotation which allows to provide SQL Scripts for a certain IT test.
* The transactional ensures that data is cleaned up after test.
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional
@Test
@Sql
public @interface TransactionalSQLTest {
@AliasFor(attribute = "value", annotation = Sql.class)
String[] value() default {};
@AliasFor(attribute = "executionPhase", annotation = Sql.class)
Sql.ExecutionPhase executionPhase() default Sql.ExecutionPhase.BEFORE_TEST_METHOD;
}
使用注释,您可以为 SQL 提供例如用于测试的样本数据。
pom.xml
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>${testcontainers.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>${testcontainers.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${testcontainers.version}</version>
<scope>test</scope>
</dependency>
这应该是MySql的依赖
<!-- https://mvnrepository.com/artifact/org.testcontainers/mysql -->
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mysql</artifactId>
<version>1.15.3</version>
<scope>test</scope>
</dependency>