Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
D

database-rider

> 后端框架
Open source

Database testing made easy!

683 stars0 likes0 views
WebsiteGitHub

About

Database testing made easy!

= Database Rider :page-layout: base :source-language: java :icons: font :linkattrs: :sectanchors: :sectlink: :numbered: :doctype: book :toc: preamble :tip-caption: :bulb: :note-caption: :information_source: :important-caption: :heavy_exclamation_mark: :caution-caption: :fire: :warning-caption: :warning:

++++

++++

[quote]


So you can ride the database in your JUnit tests!


image:https://github.com/database-rider/database-rider/actions/workflows/ci.yml/badge.svg[Build Status, link=https://github.com/database-rider/database-rider/actions/workflows/ci.yml] image:https://coveralls.io/repos/database-rider/database-rider/badge.png[Coverage, link=https://coveralls.io/r/database-rider/database-rider] image:https://img.shields.io/maven-central/v/com.github.database-rider/rider-core.svg?label=Maven%20Central["Maven Central",link="https://search.maven.org/search?q=g:com.github.database-rider"] image:https://sonarcloud.io/api/project_badges/measure?project=com.github.database-rider:rider-parent&metric=alert_status["Sonar", link="https://sonarcloud.io/dashboard?id=com.github.database-rider%3Arider-parent"] image:https://badges.gitter.im/database-rider/community.svg["Gitter", link="https://gitter.im/database-rider/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge"]

This project aims for bringing http://dbunit.sourceforge.net/[DBUnit] closer to your JUnit tests so database testing will feel like a breeze!

Watch https://www.youtube.com/watch?v=A5ryED3a8FY[1.0 promo video^] to get an idea.

A lot of this work is based on https://github.com/arquillian/arquillian-extension-persistence/[Arquillian persistence extension] and focus on simplicity (one dependency - dbunit).

== Introduction

Consider the following (jpa) entities:

[source, java]

@Entity public class User {

@Id
@GeneratedValue
private long id;

private String name;

@OneToMany(mappedBy = "user")
private List tweets;

@OneToMany(mappedBy = "followedUser")
private List followers;

//getters/setters

}

@Entity public class Tweet {

@Id
@GeneratedValue
private String id;

@Size(min = 1, max = 140)
private String content;

private Integer likes;

@Temporal(TemporalType.TIMESTAMP)
private Date date;

@ManyToOne
private User user;

}

@Entity public class Follower {

@Id
@GeneratedValue
private long id;

@JoinColumn(name = "follower_id")
private User followerUser;

@ManyToOne
@JoinColumn(name = "user_id")
private User followedUser;

}


and the following dbunit yaml dataset:

.src/test/resources/datasets/users.yml

user:

  • id: 1 name: "@realpestano"
  • id: 2 name: "@dbunit" tweet:
  • id: abcdef12345 content: "dbunit rules!" user_id: 1 follower:
  • id: 1 user_id: 1 follower_id: 2

You should be able to prepare your database before test execution, like below:

[source,java]

@RunWith(JUnit4.class) public class UserIt {

@Rule public EntityManagerProvider emProvider = EntityManagerProvider.instance("rules-it");

@Rule public DBUnitRule dbUnitRule = DBUnitRule.instance(emProvider.connection());

@Test @DataSet(value = "datasets/yml/users.yml") public void shouldLoadUserFollowers() { User user = (User) emProvider.em().createQuery("select u from User u left join fetch u.followers where u.id = 1").getSingleResult(); assertThat(user).isNotNull(); assertThat(user.getId()).isEqualTo(1); assertThat(user.getTweets()).hasSize(1); assertEquals(user.getTweets().get(0).getContent(), "dbunit rules!"); assertThat(user.getFollowers()).isNotNull().hasSize(1); Follower expectedFollower = new Follower(2,1); assertThat(user.getFollowers()).contains(expectedFollower);

}

NOTE: > is a simple JUnit rule that creates a JPA entityManager (and caches it) for each test. DBunit rule don't depend on EntityManagerProvider, it only needs a JDBC connection;

== Documentation

A getting started guide can be found here http://database-rider.github.io/getting-started/.

For main features overview see http://database-rider.github.io/database-rider/latest/documentation.html[project living documentation^].

Older documentation versions can be found here: https://database-rider.github.io/database-rider/#documentation.

== Rider Core

This module is the basis for subsequent modules. It contains a JUnit rule (shown above), the api for dataset, DBunit configuration and DataSetExecutor which is responsible for dataset creation.

=== Adding Database Rider core to your project

[source, xml]

  com.github.database-rider
  rider-core
  1.44.0
  test

TIP: Use jakarta maven classifier if you use jakarta-cdi or jakarta-persistence

[NOTE]

It will bring the following (transitive) dependencies to your test classpath:

[source,xml]

  org.dbunit
  dbunit

  org.yaml
  snakeyaml

  org.codehaus.jackson
  jackson-mapper-lgpl

====

=== DataSet executor A DataSet executor is a component which creates DBUnit datasets. Datasets are "sets" of data (tables and rows) that represent the state of the database. DataSets are defined as textual files in YAML, XML, JSON, CSV, XLS or XLSX format, https://github.com/database-rider/database-rider/blob/master/rider-core/src/test/resources/datasets/[see examples here^].

As in DBUnit Rule, dataset executor just needs a JDBC connection to be instantiated:

[source,java]

import static com.github.database.rider.util.EntityManagerProvider.em; import static com.github.database.rider.util.EntityManagerProvider.instance;

@RunWith(JUnit4.class) public class DataSetExecutorIt {

public EntityManagerProvider emProvider = instance("executor-it");

private static DataSetExecutorImpl executor;

@BeforeClass
public static void setup() {
    executor = DataSetExecutorImpl.instance(new ConnectionHolderImpl(emProvider.getConnection()));
}

@Test
public void shouldSeedUserDataSetUsingExecutor() {
     DataSetConfig dataSetConfig = new DataSetConfig("datasets/yml/users.yml");
     executor.createDataSet(dataSetConfig);
     User user = (User) em().createQuery("select u from User u where u.id = 1").getSingleResult();
     assertThat(user).isNotNull();
     assertThat(user.getId()).isEqualTo(1);
  }

}

As we are not using @Rule, which is responsible for reading @DataSet annotation, we have to provide DataSetConfig so executor can create the dataset. this is done implicitly by @Rule DBUnitRule.

DataSet executor setup and logic is hidden by DBUnit @Rule and @DataSet annotation.

[IMPORTANT]

Since v1.13.0 you can use > which provides a fluent api as an alternative to DataSetExecutor (and @DataSet):

[source,java]

import static com.github.database.rider.util.EntityManagerProvider.em; import static com.github.database.rider.util.EntityManagerProvider.instance;

@RunWith(JUnit4.class) public class DataSetExecutorIt {

public EntityManagerProvider emProvider = instance("executor-it");

@Test
public void shouldSeedUserDataSetUsingRiderDSL() {
     RiderDSL.withConnection(emProvider.getConnection())
             .withDataSetConfig(new DataSetConfig("datasets/yml/users.yml")
                               .cleanBefore(true))
             .withDBUnitConfig(new DBUnitConfig()
                               .addDBUnitProperty("caseSensitiveTableNames", false))
             .createDataSet();
     User user = (User) em().createQuery("select u from User u where u.id = 1").getSingleResult();
     assertThat(user).isNotNull();
     assertThat(user.getId()).isEqualTo(1);
  }

}

====

=== Configuration

There are two types of configuration in Database Rider: DataSet and DBUnit.

==== DataSet Configuration

This basically setup the dataset which will be used. The only way to configure a dataset is using @DataSet annotation.

It can be used at class or method level:

[source,java]

 @Test
 @DataSet(value ="users.yml", strategy = SeedStrategy.UPDATE,
        disableConstraints = true,cleanAfter = true,transactional = true)
 public void shouldLoadDataSetConfigFromAnnotation(){

  }

Here are possible values:

[cols="3*", options="header"] |=== |Name | Description | Default |value a|Dataset file name using

  • test resources folder as root directory. ** eg. 'yml/users.yml'
  • URL-Notation for registered stream-handlers ** eg. 'file:///C:/dir/users.xml', 'http://...') ** except: loading csv datasets is only supported by the file-protocol

Multiple, comma separated, dataset file names can be provided.| "" |executorId| Name of dataset executor for the given dataset.| DataSetExecutorImpl.DEFAULT_EXECUTOR_ID |strategy| DataSet seed strategy. Possible values are: CLEAN_INSERT, INSERT, REFRESH and UPDATE.| CLEAN_INSERT, meaning that DBUnit will clean and then insert data in tables present on provided dataset. |useSequenceFiltering| If true dbunit will look at constraints and dataset to try to determine the correct ordering for the SQL statements.| true |tableOrdering| A list of table names used to reorder DELETE operations to prevent failures due to circular dependencies.| "" |disableConstraints| Disable database constraints.| false |cleanBefore| If true Database Rider will try to delete database before test in a smart way by using table ordering and brute force.| false |cleanAfter| If true Database Rider will try to delete database after test in a smart way by using table ordering and brute force.| false |transactional| If true a transaction will be started before test and committed after test execution. | false |executeStatementsBefore| A list of jdbc statements to execute before test.| {} |executeStatementsAfter| A list of jdbc statements to execute after test.| {} |executeScriptsBefore| A list of sql script files to execute before test. Note that commands inside sql file must be separated by ;.| {} |executeScriptsAfter| A list of sql script files to execute after test. Note that commands inside sql file must be separated by ;.| {} |skipCleaningFor| Allows user to provide tables which will NOT be cleaned in cleanBefore and cleanAfter.| {} |replacers| Implementations of com.github.database.rider.core.replacers.Replacer to be used as dataset replacement during seeding database.| {} |===

==== DBUnit Configuration

This basically setup DBUnit itself. It can be configured by @DBUnit annotation (class or method level) and dbunit.yml file present in test resources folder.

[source,java]

@Test
@DBUnit(cacheConnection = true, cacheTableNames = false, allowEmptyFields = true,batchSize = 50)
public void shouldLoadDBUnitConfigViaAnnotation() {

}

Here is a dbunit.yml example, also the default values:

.src/test/resources/dbunit.yml

cacheConnection: true cacheTableNames: true leakHunter: false mergeDataSets: false mergingStrategy: METHOD caseInsensitiveStrategy: UPPERCASE raiseExceptionOnCleanUp: false expectedDbType: UNKNOWN disableSequenceFiltering: false disablePKCheckFor: [""] alwaysCleanBefore: false alwaysCleanAfter: false properties: batchedStatements: false qualifiedTableNames: false schema: null caseSensitiveTableNames: false batchSize: 100 fetchSize: 100 allowEmptyFields: false escapePattern: datatypeFactory: !!com.github.database.rider.core.configuration.DBUnitConfigTest$MockDataTypeFactory {} tableType: ["TABLE"] connectionConfig: driver: "" url: "" user: "" password: ""

Strategy for merging datasets, if METHOD then the method level dataset will be loaded first but if CLASS then the class level dataset will be loaded first. Only applied when caseSensitiveTableNames is false. Valid values are UPPERCASE and LOWERCASE. If enabled an exception will be rais

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Javacdidb-testingdbriderdbunit

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架