您可以将迁移文件保留在src下,无需将其复制到测试文件夹中。当运行@SpringBootTest
时,它们将被使用。这也确保您在测试中使用所有的production
迁移。
此外,您不一定需要一个单独的属性文件进行测试。但是您可以有一个。
以下是使用TestContainers
进行集成测试的示例,它使用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 { }
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;
}
<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>