-
Notifications
You must be signed in to change notification settings - Fork 4
feat(junit5): Add DbUnitExtension for JUnit 5/6 lifecycle management #912
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
154 changes: 154 additions & 0 deletions
154
src/main/java/org/dbunit/junit/jupiter/DbUnitExtension.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,154 @@ | ||
| /* | ||
| * | ||
| * The DbUnit Database Testing Framework | ||
| * Copyright (C)2002-2025, DbUnit.org | ||
| * | ||
| * This library is free software; you can redistribute it and/or | ||
| * modify it under the terms of the GNU Lesser General Public | ||
| * License as published by the Free Software Foundation; either | ||
| * version 2.1 of the License, or (at your option) any later version. | ||
| * | ||
| * This library is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | ||
| * Lesser General Public License for more details. | ||
| * | ||
| * You should have received a copy of the GNU Lesser General Public | ||
| * License along with this library; if not, write to the Free Software | ||
| * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | ||
| * | ||
| */ | ||
| package org.dbunit.junit.jupiter; | ||
|
|
||
| import java.lang.reflect.Field; | ||
| import java.lang.reflect.Modifier; | ||
|
|
||
| import org.dbunit.IDatabaseTester; | ||
| import org.junit.jupiter.api.extension.AfterTestExecutionCallback; | ||
| import org.junit.jupiter.api.extension.BeforeTestExecutionCallback; | ||
| import org.junit.jupiter.api.extension.ExtensionContext; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| /** | ||
| * JUnit 5/6 extension for DbUnit that manages the {@link IDatabaseTester} lifecycle | ||
| * around each test method. | ||
| * | ||
| * <p>Calls {@link IDatabaseTester#onSetup()} immediately before the test method | ||
| * (after all {@code @BeforeEach} callbacks) and {@link IDatabaseTester#onTearDown()} | ||
| * immediately after the test method (before any {@code @AfterEach} callbacks). | ||
| * | ||
| * <p>The extension discovers the {@link IDatabaseTester} by scanning the test | ||
| * instance's fields, including inherited fields, for a non-static field assignable | ||
| * to {@link 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 {@code @BeforeEach} method; those run before this extension's | ||
| * setup callback: | ||
| * | ||
| * <pre>{@code | ||
| * @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() { ... } | ||
| * } | ||
| * }</pre> | ||
| * | ||
| * <p><strong>Note:</strong> {@code @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. | ||
| * | ||
| * @author dbunit | ||
| * @since 3.4.1 | ||
| */ | ||
| public class DbUnitExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback { | ||
| private static final Logger log = LoggerFactory.getLogger(DbUnitExtension.class); | ||
|
|
||
| private static final ExtensionContext.Namespace NAMESPACE = | ||
| ExtensionContext.Namespace.create(DbUnitExtension.class); | ||
|
|
||
| private static final String TESTER_KEY = "databaseTester"; | ||
|
|
||
| /** | ||
| * Runs database setup before the test method executes. | ||
| * | ||
| * @param context The extension context for the test method. | ||
| * @throws Exception If resolving the {@link IDatabaseTester} field or its onSetup() call fails. | ||
| */ | ||
| @Override | ||
| public void beforeTestExecution(final ExtensionContext context) throws Exception { | ||
| final IDatabaseTester tester = resolveTester(context); | ||
| context.getStore(NAMESPACE).put(TESTER_KEY, tester); | ||
| tester.onSetup(); | ||
| } | ||
|
|
||
| /** | ||
| * Runs database teardown after the test method executes. | ||
| * | ||
| * @param context The extension context for the test method. | ||
| * @throws Exception If the stored {@link IDatabaseTester}'s onTearDown() call fails. | ||
| */ | ||
| @Override | ||
| public void afterTestExecution(final ExtensionContext context) throws Exception { | ||
| final IDatabaseTester tester = | ||
| context.getStore(NAMESPACE).get(TESTER_KEY, IDatabaseTester.class); | ||
| if (tester != null) { | ||
| tester.onTearDown(); | ||
| } | ||
| } | ||
|
|
||
| private IDatabaseTester resolveTester(final ExtensionContext context) throws Exception { | ||
| final Object testInstance = context.getTestInstance() | ||
| .orElseThrow(() -> new IllegalStateException( | ||
| "No test instance available in ExtensionContext.")); | ||
|
|
||
| Class<?> clazz = testInstance.getClass(); | ||
| while (clazz != null && clazz != Object.class) { | ||
| final Field field = findTesterField(clazz, testInstance); | ||
| if (field != null) { | ||
| field.setAccessible(true); | ||
| final IDatabaseTester tester = (IDatabaseTester) field.get(testInstance); | ||
| if (tester == null) { | ||
| throw new IllegalStateException("IDatabaseTester field '" | ||
| + field.getName() + "' in " | ||
| + testInstance.getClass().getName() + " is null."); | ||
| } | ||
| log.debug("Resolved IDatabaseTester '{}' in {}", | ||
| field.getName(), testInstance.getClass().getName()); | ||
| return tester; | ||
| } | ||
| clazz = clazz.getSuperclass(); | ||
| } | ||
|
|
||
| throw new IllegalStateException("No IDatabaseTester field found in " | ||
| + testInstance.getClass().getName() | ||
| + " or its superclasses. Declare a non-static field whose type implements IDatabaseTester" | ||
| + " to use DbUnitExtension."); | ||
|
sourcery-ai[bot] marked this conversation as resolved.
|
||
| } | ||
|
|
||
| private Field findTesterField(final Class<?> clazz, final Object testInstance) { | ||
| Field match = null; | ||
| for (final Field field : clazz.getDeclaredFields()) { | ||
| if (!Modifier.isStatic(field.getModifiers()) | ||
| && IDatabaseTester.class.isAssignableFrom(field.getType())) { | ||
| if (match != null) { | ||
| throw new IllegalStateException("Multiple IDatabaseTester fields found in " | ||
| + clazz.getName() + ": '" + match.getName() + "' and '" | ||
| + field.getName() + "'. Declare exactly one non-static field" | ||
| + " whose type implements IDatabaseTester in " | ||
| + testInstance.getClass().getName() + "."); | ||
| } | ||
| match = field; | ||
| } | ||
| } | ||
| return match; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| = DbUnitExtension | ||
| Jeff Jensen | ||
|
|
||
| == Overview | ||
|
|
||
| link:/dbunit/apidocs/org/dbunit/junit/jupiter/DbUnitExtension.html[DbUnitExtension] | ||
| is a JUnit 5/6 (Jupiter) extension that drives the | ||
| link:IDatabaseTester.html[IDatabaseTester] setup/teardown lifecycle | ||
| automatically, so a test class doesn't need its own `@BeforeEach`/`@AfterEach` | ||
| pair calling `onSetup()`/`onTearDown()`. | ||
|
|
||
| Register it with `@ExtendWith(DbUnitExtension.class)`. The test class still | ||
| holds its own `IDatabaseTester` field — this is the same composition style as | ||
| link:IDatabaseTester.html[the IDatabaseTester guide], just with the lifecycle | ||
| calls automated instead of written by hand: | ||
|
|
||
| [source,java] | ||
| ---- | ||
| @ExtendWith(DbUnitExtension.class) | ||
| class AccountRepositoryTest | ||
| { | ||
| IDatabaseTester databaseTester = | ||
| new JdbcDatabaseTester("org.h2.Driver", "jdbc:h2:mem:example;DB_CLOSE_DELAY=-1"); | ||
|
|
||
| @BeforeEach | ||
| void loadDataset() throws Exception | ||
| { | ||
| databaseTester.setDataSet(new FlatXmlDataSetBuilder().build(new File("prep.xml"))); | ||
| databaseTester.setTearDownOperation(DatabaseOperation.DELETE_ALL); | ||
| } | ||
|
|
||
| @Test | ||
| void testWithdraw_sufficientBalance_decrementsBalance() { ... } | ||
| } | ||
| ---- | ||
|
|
||
| `@BeforeEach` methods still run first — configure the dataset and any | ||
| operation overrides there. The extension then calls `onSetup()` immediately | ||
| before the test method and `onTearDown()` immediately after it, even if the | ||
| test method fails or `onSetup()` itself throws. | ||
|
|
||
| == Field Discovery | ||
|
|
||
| The extension finds the `IDatabaseTester` by scanning the test instance's | ||
| fields, including inherited ones: | ||
|
|
||
| * The nearest declaring class wins — a field on the test class itself takes | ||
| precedence over one on a superclass. | ||
| * That class must declare exactly one non-static field assignable to | ||
| `IDatabaseTester`. No match anywhere in the hierarchy, or two-or-more | ||
| matches at the same class level, both fail fast with a descriptive | ||
| `IllegalStateException` rather than guessing. | ||
| * Static fields are ignored. | ||
| * Private fields are found; the field's own access modifier doesn't matter. | ||
|
|
||
| NOTE: `@Nested` test classes are not supported — field discovery only walks | ||
| the innermost test instance and its superclasses, not enclosing class | ||
| instances, since a Java nested class does not extend its enclosing class. | ||
|
|
||
| == When to Use This Instead of Manual Lifecycle Calls | ||
|
|
||
| Reach for `DbUnitExtension` when a `@BeforeEach`/`@AfterEach` pair that only | ||
| calls `onSetup()`/`onTearDown()` (as shown in link:IDatabaseTester.html[the | ||
| IDatabaseTester guide]) would just be boilerplate repeated across every test | ||
| class. Write the `@BeforeEach`/`@AfterEach` pair yourself instead when a test | ||
| needs other logic around those calls, or targets a JUnit version this | ||
| extension doesn't support. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.