Class DbUnitExtension

java.lang.Object
org.dbunit.junit.jupiter.DbUnitExtension
All Implemented Interfaces:
org.junit.jupiter.api.extension.AfterTestExecutionCallback, org.junit.jupiter.api.extension.BeforeTestExecutionCallback, org.junit.jupiter.api.extension.Extension

public class DbUnitExtension extends Object implements org.junit.jupiter.api.extension.BeforeTestExecutionCallback, org.junit.jupiter.api.extension.AfterTestExecutionCallback
JUnit 5/6 extension for DbUnit that manages the IDatabaseTester lifecycle around each test method.

Calls IDatabaseTester.onSetup() immediately before the test method (after all @BeforeEach callbacks) and IDatabaseTester.onTearDown() immediately after the test method (before any @AfterEach callbacks).

The extension discovers the IDatabaseTester by scanning the test instance's fields, including inherited fields, for a non-static field assignable to IDatabaseTester: the nearest declaring class (test class before superclass) wins, but that class must declare exactly one such field—two or more at the same level is rejected as ambiguous. Configure the tester—including its dataset—in a @BeforeEach method; those run before this extension's setup callback:


 @ExtendWith(DbUnitExtension.class)
 class MyDatabaseTest {
     IDatabaseTester databaseTester = new JdbcDatabaseTester("driver", "url", "user", "pass");

     @BeforeEach
     void loadDataset() throws Exception {
         databaseTester.setDataSet(new FlatXmlDataSetBuilder().build(...));
     }

     @Test
     void testSomething() { ... }
 }
 

Note: @Nested test classes are not supported. Field discovery only scans the innermost test instance and its superclasses—not enclosing class instances—since a Java nested class does not extend its enclosing class.

Since:
3.5.0
Author:
dbunit
  • Constructor Details

    • DbUnitExtension

      public DbUnitExtension()
  • Method Details

    • beforeTestExecution

      public void beforeTestExecution(org.junit.jupiter.api.extension.ExtensionContext context) throws Exception
      Runs database setup before the test method executes.
      Specified by:
      beforeTestExecution in interface org.junit.jupiter.api.extension.BeforeTestExecutionCallback
      Parameters:
      context - The extension context for the test method.
      Throws:
      Exception - If resolving the IDatabaseTester field or its onSetup() call fails.
    • afterTestExecution

      public void afterTestExecution(org.junit.jupiter.api.extension.ExtensionContext context) throws Exception
      Runs database teardown after the test method executes.
      Specified by:
      afterTestExecution in interface org.junit.jupiter.api.extension.AfterTestExecutionCallback
      Parameters:
      context - The extension context for the test method.
      Throws:
      Exception - If the stored IDatabaseTester's onTearDown() call fails.