use*_*342 7 postgresql spring-boot spring-boot-test testcontainers
I am using an abstract class like this:
@SpringBootTest(classes = MyAppApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public abstract class AbstractIntegrationTest {
static {
PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer().withPassword("password")
.withUsername("postgres").withDatabaseName("MyApp");
postgreSQLContainer.start();
System.setProperty("spring.datasource.url", postgreSQLContainer.getJdbcUrl());
System.setProperty("spring.datasource.password", postgreSQLContainer.getPassword());
System.setProperty("spring.datasource.username", postgreSQLContainer.getUsername());
}
Run Code Online (Sandbox Code Playgroud)
Then I have many tests that leverage that use that class like this:
public class moreTests extends AbstractIntegrationTest {
TestRestTemplate restTemplate = new TestRestTemplate("my-user", "password");
HttpHeaders headers = new HttpHeaders();
@Test
public void SimpleHealthCheck() {
HttpEntity<String> entity = new HttpEntity<String>(null, headers);
ResponseEntity<String> response = restTemplate.exchange(
createURLWithPort("/api/v1/healthcheck"),
HttpMethod.GET, entity, String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void GetInst() {
HttpEntity<String> entity = new HttpEntity<String>(null, headers);
ResponseEntity<String> response = restTemplate.exchange(
createURLWithPort("/api/v1/institutions"),
HttpMethod.GET, entity, String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
Run Code Online (Sandbox Code Playgroud)
However, some of my tests will pollute the database. I'd like to control if a test runs with a fresh database or not. What's the prescribed way to do this?
在更多地阅读有关 Spring boot 集成测试的内容之后,似乎规定的方法是使用“@DirtiesContext”注释进行破坏性(或脏)测试。
编辑:几个月后,我意识到 @DirtiesContext 并不好。它基本上会重置整个应用程序,这可能会很昂贵。此外,@DirtiesContext 在某些情况下可能不会重置您的数据库,具体取决于您的应用程序的工作方式。我建议在每个测试类的 @BeforeAll 或 @AfterAll 部分中运行一个清理 SQL 脚本。这个清理 SQL 脚本需要仔细编写。
| 归档时间: |
|
| 查看次数: |
8859 次 |
| 最近记录: |