public class AbstractContainerBaseTest {
@ServiceConnection
static final MySQLContainer<?> MY_SQL_CONTAINER = new MySQLContainer<>("mysql:8.0.32")
static {
MY_SQL_CONTAINER.start();
}
}
class FirstTest extends AbstractContainerBaseTest {
@Test
void someTestMethod() {
}
}
I have a AbstractContainerBaseTest and other test classes will extend it. I encounter problem when running all test classes some test methods will fail but when I only run the test classes individually containing of said methods they will pass. As far as I understand all test classes share a same container so my question is how to reset DB after each test class?
public class AbstractContainerBaseTest {
@ServiceConnection
static final MySQLContainer<?> MY_SQL_CONTAINER = new MySQLContainer<>("mysql:8.0.32")
static {
MY_SQL_CONTAINER.start();
}
}
class FirstTest extends AbstractContainerBaseTest {
@Test
void someTestMethod() {
}
}
I have a AbstractContainerBaseTest and other test classes will extend it. I encounter problem when running all test classes some test methods will fail but when I only run the test classes individually containing of said methods they will pass. As far as I understand all test classes share a same container so my question is how to reset DB after each test class?
Share Improve this question asked Mar 3 at 2:49 Frank CastleFrank Castle 13 bronze badges 3- Could you please provide logs for failed test cases this will help us to find the root cause – – Deepak Commented Mar 3 at 6:45
- If you want to reset database basically you want to perform a DML you can easily do it via java + Mysql integration – Deepak Commented Mar 3 at 6:47
- @Deepak failed test cases are just simply the asserts fail – Frank Castle Commented Mar 3 at 7:02
2 Answers
Reset to default 0You can try
@TestInstance(TestInstance.Lifecycle.PER_CLASS) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
You can write a simple extension for reset data on your tables!
e.g
public class CleanupDatabaseExtension implements BeforeEachCallback {
@Override
public void beforeEach(final ExtensionContext context) {
final var applicationContext = SpringExtension.getApplicationContext(context);
applicationContext.getBeansWithAnnotation(Repository.class)
.values()
.forEach(repository -> ((JpaRepository<?, ?>) repository).deleteAllInBatch());
}
}
In your test class, use:
@ExtendedWith(CleanupDatabaseExtension.class)
public class MyTest {
// your tests
}
IMPORTANT: This code doesn't cover the relationships on your schema. If you need to delete with some order to respect the FK restrictions, write the deletion statements in order.