gpt4 book ai didi

postgresql - SpringbootTest + TestContainers : how do I refresh the database after tests pollute the database

转载 作者:行者123 更新时间:2023-12-03 22:07:36 25 4
gpt4 key购买 nike

我正在使用这样的抽象类:

@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());

}

然后我有很多测试可以利用这样的类:
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));
}

但是,我的一些测试会污染数据库。我想控制测试是否使用新数据库运行。这样做的规定方法是什么?

最佳答案

在详细阅读 Spring boot 集成测试之后,似乎规定的方法是对具有破坏性(或脏)的测试使用“@DirtiesContext”注释。
编辑:几个月后,我意识到@DirtiesContext 并不棒。它基本上会重置整个应用程序,这可能很昂贵。此外,在某些情况下,@DirtiesContext 可能不会重置您的数据库,具体取决于您的应用程序的工作方式。我建议在每个测试类的 @BeforeAll 或 @AfterAll 部分运行一个清理 SQL 脚本。这个清理SQL脚本需要仔细编写。

关于postgresql - SpringbootTest + TestContainers : how do I refresh the database after tests pollute the database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56367640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com