Below are some of the classes that support @TestContainers functionality
package com.changeorama.solidify;
import static org.junit.Assert.assertTrue;
import org.junit.jupiter.api.Test;
....
@Testcontainers
public class AbstractTest {
@Container
private static final PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>();
static {
postgres.start();
}
@Test
void testPostgresIsRunning() {
assertTrue(postgres.isRunning());
}
@DynamicPropertySource
static void postgreSQLProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
}
package com.changeorama.solidify.repository;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.junit.jupiter.api.Test;
....
import lombok.extern.slf4j.Slf4j;
@Slf4j
@ActiveProfiles(profiles = "test")
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class CompartmentRepositoryTest extends AbstractTest{
@Autowired
CompartmentRepository compRepository;
@Test
void testSaveCompartment() {
//Load test data
CompartmentEntity comp = new CompartmentEntity();
comp.setCompartmentId(12);
comp.setCompartmentName(“Comp abc”);
comp.setCompartmentSize(12);
compRepository(comp);
}
@Test
void testGetAllCompartments() {
List<CompartmentEntity> comps = compRepository.findAll();
assertThat(comps.isEmpty(), is(false));
}
}
Is there a way clean up the data in between tests that run in the same test suite with the @Testcontainers approach?
Do we have an ability to do a purge of the database in between tests?
Is there anyway we can do a manual purge of data if not possible with @TestContainers?
Annotate your test class with @Transactional
@Slf4j
@ActiveProfiles(profiles = "test")
@DataJpaTest
@Transactional
@AutoConfigureTestDatabase(replace=AutoConfigureTestDatabase.Replace.NONE)
public class CompartmentRepositoryTest extends AbstractTest{
//then your code
}
When a test class is annotated with @Transactional
each test method within
that class hierarchy runs within a transaction that is by default it will rollback automatically after completion.
Note that
@Transactional
is not supported on test lifecycle methods.
Tests that are annotated with @Transactional
but have the propagation attribute set to NOT_SUPPORTED
(@Transactional = Propagation.NOT_SUPPORTED
) are not run within a transaction.
You can use @Rollback
on class level or test method
@Test
@Rollback(true)
void testSaveCompartment() {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With