Skip to content

Instantly share code, notes, and snippets.

@vladdedita
Last active November 21, 2024 23:12
Show Gist options
  • Save vladdedita/391c502aa3c568194b2011b91c19209a to your computer and use it in GitHub Desktop.
Save vladdedita/391c502aa3c568194b2011b91c19209a to your computer and use it in GitHub Desktop.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ClutteredTest {
private static final PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:latest")
.withDatabaseName("testdb")
.withUsername("testuser")
.withPassword("testpass");
@BeforeAll
static void setUp() throws IOException, InterruptedException {
postgres.start();
postgres.execInContainer("psql", "-U", "testuser", "-d", "testdb", "-c", "CREATE TABLE public.user (id SERIAL PRIMARY KEY, name TEXT)");
postgres.execInContainer("psql", "-U", "testuser", "-d", "testdb", "-c", "INSERT INTO public.user (name) VALUES ('Alice'), ('Bob')");
}
@AfterAll
static void tearDown() {
postgres.stop();
}
@DynamicPropertySource
static void registerDynamicProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
@Autowired
EntityManager entityManager;
@Test
@Transactional
void testUserCreation() {
// Query data
var result = entityManager.createNativeQuery("SELECT COUNT(*) FROM public.user").getSingleResult();
assertThat(result).isEqualTo(2L);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment