org.unitils.database
Class DatabaseModule

java.lang.Object
  extended by org.unitils.database.DatabaseModule
All Implemented Interfaces:
Module

public class DatabaseModule
extends Object
implements Module

Module that provides support for database testing: Creation of a datasource that connects to the test database, support for executing tests in a transaction and automatic maintenance of the test database.

A datasource will be created the first time one is requested. Which type of datasource will be created depends on the configured DataSourceFactory. By default this will be a pooled datasource that gets its connection-url, username and password from the unitils configuration.

The created datasource can be injected into a field of the test by annotating the field with TestDataSource. It can then be used to install it in your DAO or other class under test.

If the DBMaintainer is enabled (by setting PROPERTY_UPDATEDATABASESCHEMA_ENABLED to true), the test database schema will automatically be updated if needed. This check will be performed once during your test-suite run, namely when the data source is created.

If the test class or method is annotated with Transactional with transaction mode TransactionMode.COMMIT or TransactionMode.ROLLBACK, or if the property 'DatabaseModule.Transactional.value.default' was set to 'commit' or 'rollback', every test is executed in a transaction.

Author:
Filip Neven, Tim Ducheyne
See Also:
TestDataSource, DBMaintainer, Transactional

Nested Class Summary
protected  class DatabaseModule.DatabaseTestListener
          The TestListener for this module
 
Field Summary
protected  Properties configuration
          The configuration of Unitils
protected  DataSource dataSource
          The datasources with the name as key
protected  Map<Class<? extends Annotation>,Map<String,String>> defaultAnnotationPropertyValues
          Map holding the default configuration of the database module annotations
static String PROPERTY_UPDATEDATABASESCHEMA_ENABLED
          Property indicating if the database schema should be updated before performing the tests
static String PROPERTY_WRAP_DATASOURCE_IN_TRANSACTIONAL_PROXY
          Property indicating whether the datasource injected onto test fields annotated with @TestDataSource or retrieved using getTransactionalDataSourceAndActivateTransactionIfNeeded(Object) must be wrapped in a transactional proxy
protected  Set<UnitilsTransactionManagementConfiguration> transactionManagementConfigurations
          Set of possible providers of a spring PlatformTransactionManager
protected  UnitilsTransactionManager transactionManager
          The transaction manager
protected  boolean updateDatabaseSchemaEnabled
          Indicates if the DBMaintainer should be invoked to update the database
protected  boolean wrapDataSourceInTransactionalProxy
          Indicates whether the datasource injected onto test fields annotated with @TestDataSource or retrieved using getTransactionalDataSourceAndActivateTransactionIfNeeded(java.lang.Object) must be wrapped in a transactional proxy
 
Constructor Summary
DatabaseModule()
           
 
Method Summary
 void activateTransactionIfNeeded()
           
 void afterInit()
          Initializes the spring support object
 void cleanSchemas()
          Cleans all configured schema's.
 void clearSchemas()
          Clears all configured schema's.
 void commitTransaction(Object testObject)
          Commits the current transaction.
protected  DataSource createDataSource()
          Creates a datasource by using the factory that is defined by the dataSourceFactory.className property
 void disableConstraints()
          Disables all foreigh key and not-null constraints on the configured schema's.
protected  void endTransactionForTestMethod(Object testObject, Method testMethod)
          Commits or rollbacks the current transaction, if transactions are enabled and a transactionManager is active for the given testObject
 void flushDatabaseUpdates(Object testObject)
          Flushes all pending updates to the database.
 void generateDatasetDefinition()
          Generates a definition file that defines the structure of dataset's, i.e. a XSD of DTD that describes the structure of the database.
protected
<T extends DatabaseAccessing>
T
getConfiguredDatabaseTaskInstance(Class<T> databaseTaskType)
           
 DataSource getDataSource()
           
 DataSource getDataSourceAndActivateTransactionIfNeeded()
          Returns the DataSource that provides connection to the unit test database.
protected  SQLHandler getDefaultSqlHandler()
           
 TestListener getTestListener()
          Creates the test listener for this module.
protected  Object getTestObject()
           
 DataSource getTransactionalDataSourceAndActivateTransactionIfNeeded(Object testObject)
          Returns the DataSource that provides connection to the unit test database.
 UnitilsTransactionManager getTransactionManager()
          Returns the transaction manager or creates one if it does not exist yet.
protected  TransactionMode getTransactionMode(Object testObject, Method testMethod)
           
 void init(Properties configuration)
          Initializes this module using the given Configuration
 void injectDataSource(Object testObject)
          Assigns the TestDataSource to every field annotated with TestDataSource and calls all methods annotated with TestDataSource
 boolean isDataSourceLoaded()
           
 boolean isTransactionsEnabled(Object testObject, Method testMethod)
           
 void registerTransactionManagementConfiguration(UnitilsTransactionManagementConfiguration transactionManagementConfiguration)
           
 void resetDatabaseState()
          Updates the database version to the current version, without issuing any other update to the database.
 void resetDatabaseState(SQLHandler sqlHandler)
          Updates the database version to the current version, without issuing any other updates to the database.
 void rollbackTransaction(Object testObject)
          Performs a rollback of the current transaction
 void startTransaction(Object testObject)
          Starts a new transaction on the transaction manager configured in unitils
protected  void startTransactionForTestMethod(Object testObject, Method testMethod)
          Starts a transaction.
 void updateDatabase()
          Determines whether the test database is outdated and, if this is the case, updates the database with the latest changes.
 void updateDatabase(SQLHandler sqlHandler)
          Determines whether the test database is outdated and, if that is the case, updates the database with the latest changes.
 void updateSequences()
          Updates all sequences that have a value below a certain configurable treshold to become equal to this treshold
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

PROPERTY_UPDATEDATABASESCHEMA_ENABLED

public static final String PROPERTY_UPDATEDATABASESCHEMA_ENABLED
Property indicating if the database schema should be updated before performing the tests

See Also:
Constant Field Values

PROPERTY_WRAP_DATASOURCE_IN_TRANSACTIONAL_PROXY

public static final String PROPERTY_WRAP_DATASOURCE_IN_TRANSACTIONAL_PROXY
Property indicating whether the datasource injected onto test fields annotated with @TestDataSource or retrieved using getTransactionalDataSourceAndActivateTransactionIfNeeded(Object) must be wrapped in a transactional proxy

See Also:
Constant Field Values

defaultAnnotationPropertyValues

protected Map<Class<? extends Annotation>,Map<String,String>> defaultAnnotationPropertyValues
Map holding the default configuration of the database module annotations


dataSource

protected DataSource dataSource
The datasources with the name as key


configuration

protected Properties configuration
The configuration of Unitils


updateDatabaseSchemaEnabled

protected boolean updateDatabaseSchemaEnabled
Indicates if the DBMaintainer should be invoked to update the database


wrapDataSourceInTransactionalProxy

protected boolean wrapDataSourceInTransactionalProxy
Indicates whether the datasource injected onto test fields annotated with @TestDataSource or retrieved using getTransactionalDataSourceAndActivateTransactionIfNeeded(java.lang.Object) must be wrapped in a transactional proxy


transactionManager

protected UnitilsTransactionManager transactionManager
The transaction manager


transactionManagementConfigurations

protected Set<UnitilsTransactionManagementConfiguration> transactionManagementConfigurations
Set of possible providers of a spring PlatformTransactionManager

Constructor Detail

DatabaseModule

public DatabaseModule()
Method Detail

init

public void init(Properties configuration)
Initializes this module using the given Configuration

Specified by:
init in interface Module
Parameters:
configuration - The config, not null

afterInit

public void afterInit()
Initializes the spring support object

Specified by:
afterInit in interface Module

getTransactionalDataSourceAndActivateTransactionIfNeeded

public DataSource getTransactionalDataSourceAndActivateTransactionIfNeeded(Object testObject)
Returns the DataSource that provides connection to the unit test database. When invoked the first time, the DBMaintainer is invoked to make sure the test database is up-to-date (if database updating is enabled) If the property PROPERTY_WRAP_DATASOURCE_IN_TRANSACTIONAL_PROXY has been set to true, the DataSource returned will make sure that, for the duration of a transaction, the same java.sql.Connection is returned, and that invocations of the close() method of these connections are suppressed.

Parameters:
testObject - The test instance, not null
Returns:
The DataSource

getDataSourceAndActivateTransactionIfNeeded

public DataSource getDataSourceAndActivateTransactionIfNeeded()
Returns the DataSource that provides connection to the unit test database. When invoked the first time, the DBMaintainer is invoked to make sure the test database is up-to-date (if database updating is enabled)

Returns:
The DataSource

getDataSource

public DataSource getDataSource()

activateTransactionIfNeeded

public void activateTransactionIfNeeded()

isDataSourceLoaded

public boolean isDataSourceLoaded()

getTransactionManager

public UnitilsTransactionManager getTransactionManager()
Returns the transaction manager or creates one if it does not exist yet.

Returns:
The transaction manager, not null

flushDatabaseUpdates

public void flushDatabaseUpdates(Object testObject)
Flushes all pending updates to the database. This method is useful when the effect of updates needs to be checked directly on the database.

Will look for modules that implement Flushable and call Flushable.flushDatabaseUpdates(Object) on these modules.

Parameters:
testObject - The test object, not null

updateDatabase

public void updateDatabase()
Determines whether the test database is outdated and, if this is the case, updates the database with the latest changes. See DBMaintainer for more information.


updateDatabase

public void updateDatabase(SQLHandler sqlHandler)
Determines whether the test database is outdated and, if that is the case, updates the database with the latest changes.

Parameters:
sqlHandler - SQLHandler that needs to be used for the database updates
See Also:
DBMaintainer}

resetDatabaseState

public void resetDatabaseState()
Updates the database version to the current version, without issuing any other update to the database. This method can be used for example after you've manually brought the database to the latest version, but the database version is not yet set to the current one. This method can also be useful for example for reinitializing the database after having reorganized the scripts folder.


resetDatabaseState

public void resetDatabaseState(SQLHandler sqlHandler)
Updates the database version to the current version, without issuing any other updates to the database. This method can be used for example after you've manually brought the database to the latest version, but the database version is not yet set to the current one. This method can also be useful for example for reinitializing the database after having reorganized the scripts folder.

Parameters:
sqlHandler - The DefaultSQLHandler to which all commands are issued

injectDataSource

public void injectDataSource(Object testObject)
Assigns the TestDataSource to every field annotated with TestDataSource and calls all methods annotated with TestDataSource

Parameters:
testObject - The test instance, not null

createDataSource

protected DataSource createDataSource()
Creates a datasource by using the factory that is defined by the dataSourceFactory.className property

Returns:
the datasource

getTransactionMode

protected TransactionMode getTransactionMode(Object testObject,
                                             Method testMethod)
Parameters:
testObject - The test object, not null
testMethod - The test method, not null
Returns:
The TransactionMode for the given object

startTransactionForTestMethod

protected void startTransactionForTestMethod(Object testObject,
                                             Method testMethod)
Starts a transaction. If the Unitils DataSource was not loaded yet, we simply remember that a transaction was started but don't actually start it. If the DataSource is loaded within this test, the transaction will be started immediately after loading the DataSource.

Parameters:
testObject - The test object, not null
testMethod - The test method, not null

endTransactionForTestMethod

protected void endTransactionForTestMethod(Object testObject,
                                           Method testMethod)
Commits or rollbacks the current transaction, if transactions are enabled and a transactionManager is active for the given testObject

Parameters:
testObject - The test object, not null
testMethod - The test method, not null

startTransaction

public void startTransaction(Object testObject)
Starts a new transaction on the transaction manager configured in unitils

Parameters:
testObject - The test object, not null

commitTransaction

public void commitTransaction(Object testObject)
Commits the current transaction.

Parameters:
testObject - The test object, not null

rollbackTransaction

public void rollbackTransaction(Object testObject)
Performs a rollback of the current transaction

Parameters:
testObject - The test object, not null

isTransactionsEnabled

public boolean isTransactionsEnabled(Object testObject,
                                     Method testMethod)
Parameters:
testObject - The test object, not null
testMethod - The test method, not null
Returns:
Whether transactions are enabled for the given test method and test object

clearSchemas

public void clearSchemas()
Clears all configured schema's. I.e. drops all tables, views and other database objects.


cleanSchemas

public void cleanSchemas()
Cleans all configured schema's. I.e. removes all data from its database tables.


disableConstraints

public void disableConstraints()
Disables all foreigh key and not-null constraints on the configured schema's.


updateSequences

public void updateSequences()
Updates all sequences that have a value below a certain configurable treshold to become equal to this treshold


generateDatasetDefinition

public void generateDatasetDefinition()
Generates a definition file that defines the structure of dataset's, i.e. a XSD of DTD that describes the structure of the database.


getConfiguredDatabaseTaskInstance

protected <T extends DatabaseAccessing> T getConfiguredDatabaseTaskInstance(Class<T> databaseTaskType)
Parameters:
databaseTaskType - The type of database task, not null
Returns:
A configured instance of DatabaseAccessing of the given type

getDefaultSqlHandler

protected SQLHandler getDefaultSqlHandler()
Returns:
The default SQLHandler, which simply executes the sql statements on the unitils-configured test database

registerTransactionManagementConfiguration

public void registerTransactionManagementConfiguration(UnitilsTransactionManagementConfiguration transactionManagementConfiguration)

getTestObject

protected Object getTestObject()

getTestListener

public TestListener getTestListener()
Description copied from interface: Module
Creates the test listener for this module.

Specified by:
getTestListener in interface Module
Returns:
The DatabaseModule.DatabaseTestListener associated with this module


Copyright © 2011. All Rights Reserved.