0
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?

3
  • Could you please provide logs for failed test cases this will help us to find the root cause – 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 Commented Mar 3 at 6:47
  • @Deepak failed test cases are just simply the asserts fail Commented Mar 3 at 7:02

2 Answers 2

0

You can try @TestInstance(TestInstance.Lifecycle.PER_CLASS) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.