【发布时间】:2021-10-28 02:16:06
【问题描述】:
我正在使用带有 Junit 5 的 Spring-boot 2.5.3
我正在尝试使用 PostgresSQL 测试容器进行测试。我需要将同一个测试容器用于集成测试和存储库测试,因为它在 Docker 中有两个实例。
这是我初始化容器的基类。
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.PostgreSQLContainer;
public class PostgresTestContainer {
static final PostgreSQLContainer postgreSQLContainer;
static {
postgreSQLContainer = (PostgreSQLContainer) new PostgreSQLContainer("postgres:12")
.withDatabaseName("test")
.withUsername("postgres")
.withPassword("postgres")
.withReuse(true);
postgreSQLContainer.start();
}
@DynamicPropertySource
static void datasourceConfig(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgreSQLContainer::getJdbcUrl);
registry.add("spring.datasource.password", postgreSQLContainer::getPassword);
registry.add("spring.datasource.username", postgreSQLContainer::getUsername);
}
}
这是存储库测试。
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class CustomerRepositoryTest extends PostgresTestContainer {
@Autowired
private CustomerRepository customerRepository;
@Test
@Sql("/scripts/import.sql")
public void findAllShouldGetAllCustomers() {
List<Customer> foundCustomers = customerRepository.findAll();
assertThat(foundCustomers).isNotNull();
assertThat(foundCustomers.size()).isEqualTo(3);
}
}
这是另一个我需要使用相同测试容器的地方。
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class BasicIT extends PostgresTestContainer {
@Autowired
private TestRestTemplate testRestTemplate;
@MockBean
private CustomerRepository customerRepository;
@Test
void shouldFailFetchingCustomersWhenDatabaseIsDown() {
when(customerRepository.findAll()).thenThrow(new RuntimeException("Cannot connect to database."));
ResponseEntity<String> result = this.testRestTemplate
.exchange("/api/v1/customers", HttpMethod.GET, HttpEntity.EMPTY, String.class);
assertEquals(500, result.getStatusCodeValue());
}
@Test
public void shouldFetchAListOfCustomers(){
ResponseEntity<List<Customer>> result = this.testRestTemplate
.exchange("/api/v1/customers", HttpMethod.GET, HttpEntity.EMPTY, new ParameterizedTypeReference<>() {});
assertEquals(200, result.getStatusCodeValue());
}
}
跑步:
mvn clean install
这可行,所有测试都会运行。
但它会打开两个容器,如此处的 Docker 映像所示。
【问题讨论】:
标签: java spring-boot spring-boot-test testcontainers