2 * Copyright 2005 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org.wamblee.test;
19 import java.sql.Connection;
20 import java.sql.PreparedStatement;
21 import java.sql.ResultSet;
22 import java.sql.SQLException;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.Iterator;
26 import java.util.List;
28 import java.util.TreeMap;
30 import javax.sql.DataSource;
32 import junit.framework.TestCase;
34 import org.apache.commons.logging.Log;
35 import org.apache.commons.logging.LogFactory;
36 import org.dbunit.DatabaseUnitException;
37 import org.dbunit.database.DatabaseConnection;
38 import org.dbunit.database.DatabaseSequenceFilter;
39 import org.dbunit.database.IDatabaseConnection;
40 import org.dbunit.dataset.FilteredDataSet;
41 import org.dbunit.dataset.IDataSet;
42 import org.dbunit.dataset.filter.ITableFilter;
43 import org.dbunit.operation.DatabaseOperation;
44 import org.hibernate.SessionFactory;
45 import org.jmock.cglib.MockObjectTestCase;
46 import org.springframework.beans.factory.NoSuchBeanDefinitionException;
47 import org.springframework.beans.factory.config.BeanDefinition;
48 import org.springframework.beans.factory.support.RootBeanDefinition;
49 import org.springframework.context.ApplicationContext;
50 import org.springframework.context.support.ClassPathXmlApplicationContext;
51 import org.springframework.context.support.GenericApplicationContext;
52 import org.springframework.jdbc.core.JdbcTemplate;
53 import org.springframework.jdbc.datasource.DataSourceUtils;
54 import org.springframework.jdbc.datasource.DriverManagerDataSource;
55 import org.springframework.orm.hibernate3.HibernateTemplate;
56 import org.springframework.transaction.PlatformTransactionManager;
57 import org.springframework.transaction.TransactionDefinition;
58 import org.springframework.transaction.TransactionStatus;
59 import org.springframework.transaction.support.DefaultTransactionDefinition;
60 import org.springframework.transaction.support.TransactionCallback;
61 import org.springframework.transaction.support.TransactionCallbackWithoutResult;
62 import org.springframework.transaction.support.TransactionTemplate;
63 import org.wamblee.general.BeanKernel;
64 import org.wamblee.persistence.hibernate.HibernateMappingFiles;
67 * Test case support class for spring tests.
69 public class SpringTestCase extends MockObjectTestCase {
71 private static final Log LOG = LogFactory.getLog(SpringTestCase.class);
74 * Session factory bean name.
76 private static final String SESSION_FACTORY = "sessionFactory";
79 * Data source bean name.
81 private static final String DATA_SOURCE = "dataSource";
84 * Transaction manager bean name.
86 private static final String TRANSACTION_MANAGER = "transactionManager";
89 * Name of the ConfigFileList bean that describes the Hibernate mapping
92 private static final String HIBERNATE_CONFIG_FILES = "hibernateMappingFiles";
97 private static final String SCHEMA_PATTERN = "%";
100 * List of (String) configuration file locations for spring.
102 private String[] _configLocations;
105 * Application context for storing bean definitions that vary on a test by
106 * test basis and cannot be hardcoded in the spring configuration files.
108 private GenericApplicationContext _parentContext;
111 * Cached spring application context.
113 private ApplicationContext _context;
115 public SpringTestCase(Class<? extends SpringConfigFiles> aSpringFiles,
116 Class<? extends HibernateMappingFiles> aMappingFiles) {
118 SpringConfigFiles springFiles = aSpringFiles.newInstance();
119 _configLocations = springFiles.toArray(new String[0]);
120 } catch (Exception e) {
121 fail("Could not construct spring config files class '"
122 + aSpringFiles.getName() + "'");
125 // Register the Hibernate mapping files as a bean.
126 _parentContext = new GenericApplicationContext();
127 BeanDefinition lDefinition = new RootBeanDefinition(aMappingFiles);
128 _parentContext.registerBeanDefinition(HIBERNATE_CONFIG_FILES,
130 _parentContext.refresh();
135 * Gets the spring context.
137 * @return Spring context.
139 protected synchronized ApplicationContext getSpringContext() {
140 if (_context == null) {
141 _context = new ClassPathXmlApplicationContext(
142 (String[]) _configLocations, _parentContext);
148 * @return Hibernate session factory.
150 protected SessionFactory getSessionFactory() {
151 SessionFactory factory = (SessionFactory) getSpringContext().getBean(
153 assertNotNull(factory);
157 protected void setUp() throws Exception {
158 LOG.info("Performing setUp()");
162 _context = null; // make sure we get a new application context for
166 BeanKernel.overrideBeanFactory(new TestSpringBeanFactory(
167 getSpringContext()));
175 * @see junit.framework.TestCase#tearDown()
178 protected void tearDown() throws Exception {
182 LOG.info("tearDown() complete");
187 * @return Transaction manager
189 protected PlatformTransactionManager getTransactionManager() {
190 PlatformTransactionManager manager = (PlatformTransactionManager) getSpringContext()
191 .getBean(TRANSACTION_MANAGER);
192 assertNotNull(manager);
197 * @return Starts a new transaction.
199 protected TransactionStatus getTransaction() {
200 DefaultTransactionDefinition def = new DefaultTransactionDefinition();
201 def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
203 return getTransactionManager().getTransaction(def);
207 * Returns the hibernate template for executing hibernate-specific
210 * @return Hibernate template.
212 protected HibernateTemplate getTemplate() {
213 HibernateTemplate template = (HibernateTemplate) getSpringContext()
214 .getBean(HibernateTemplate.class.getName());
215 assertNotNull(template);
220 * Flushes the session. Should be called after some Hibernate work and
221 * before JDBC is used to check results.
224 protected void flush() {
225 getTemplate().flush();
229 * Flushes the session first and then removes all objects from the Session
230 * cache. Should be called after some Hibernate work and before JDBC is used
234 protected void clear() {
236 getTemplate().clear();
240 * Evicts the object from the session. This is essential for the
241 * implementation of unit tests where first an object is saved and is
242 * retrieved later. By removing the object from the session, Hibernate must
243 * retrieve the object again from the database.
247 protected void evict(Object aObject) {
248 getTemplate().evict(aObject);
252 * Gets the connection.
254 * @return Connection.
256 public Connection getConnection() {
257 return DataSourceUtils.getConnection(getDataSource());
260 public void cleanDatabase() throws SQLException {
262 if (!isDatabaseConfigured()) {
266 String[] tables = getTableNames();
269 IDatabaseConnection connection = new DatabaseConnection(
271 ITableFilter filter = new DatabaseSequenceFilter(connection, tables);
272 IDataSet dataset = new FilteredDataSet(filter, connection
273 .createDataSet(tables));
275 DatabaseOperation.DELETE_ALL.execute(connection, dataset);
276 } catch (DatabaseUnitException e) {
277 SQLException exc = new SQLException(e.getMessage());
284 * @throws SQLException
286 public String[] getTableNames() throws SQLException {
288 List<String> result = new ArrayList<String>();
289 LOG.debug("Getting database table names to clean (schema: '"
290 + SCHEMA_PATTERN + "'");
292 ResultSet tables = getConnection().getMetaData().getTables(null,
293 SCHEMA_PATTERN, "%", new String[] { "TABLE" });
294 while (tables.next()) {
295 String table = tables.getString("TABLE_NAME");
296 // Make sure we do not touch hibernate's specific
297 // infrastructure tables.
298 if (!table.toLowerCase().startsWith("hibernate")) {
300 LOG.debug("Adding " + table
301 + " to list of tables to be cleaned.");
304 return (String[]) result.toArray(new String[0]);
309 * @throws SQLException
311 public void emptyTables(List aTableList) throws SQLException {
312 Iterator liTable = aTableList.iterator();
313 while (liTable.hasNext()) {
314 emptyTable((String) liTable.next());
320 * @throws SQLException
322 public void emptyTable(String aTable) throws SQLException {
323 executeSql("delete from " + aTable);
328 * @throws SQLException
330 public void dropTable(String aTable) throws SQLException {
331 executeQuery("drop table " + aTable);
335 * Executes an SQL statement within a transaction.
339 * @return Return code of the corresponding JDBC call.
341 public int executeSql(final String aSql) {
342 return executeSql(aSql, new Object[0]);
346 * Executes an SQL statement within a transaction. See
347 * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
348 * supported argument types.
353 * Argument of the sql statement.
354 * @return Return code of the corresponding JDBC call.
356 public int executeSql(final String aSql, final Object aArg) {
357 return executeSql(aSql, new Object[] { aArg });
361 * Executes an sql statement. See
362 * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
363 * supported argument types.
366 * SQL query to execute.
369 * @return Number of rows updated.
371 public int executeSql(final String aSql, final Object[] aArgs) {
372 Map results = executeTransaction(new TestTransactionCallback() {
373 public Map execute() throws Exception {
374 JdbcTemplate template = new JdbcTemplate(getDataSource());
375 int result = template.update(aSql, aArgs);
377 Map<String, Integer> map = new TreeMap<String, Integer>();
378 map.put("result", new Integer(result));
384 return ((Integer) results.get("result")).intValue();
388 * Executes a transaction with a result.
391 * Callback to do your transactional work.
394 public Object executeTransaction(TransactionCallback aCallback) {
395 TransactionTemplate lTemplate = new TransactionTemplate(
396 getTransactionManager());
397 return lTemplate.execute(aCallback);
401 * Executes a transaction without a result.
404 * Callback to do your transactional work. .
406 protected void executeTransaction(TransactionCallbackWithoutResult aCallback) {
407 TransactionTemplate template = new TransactionTemplate(
408 getTransactionManager());
409 template.execute(aCallback);
413 * Executes a transaction with a result, causing the testcase to fail if any
414 * type of exception is thrown.
417 * Code to be executed within the transaction.
420 public Map executeTransaction(final TestTransactionCallback aCallback) {
421 return (Map) executeTransaction(new TransactionCallback() {
422 public Object doInTransaction(TransactionStatus aArg) {
424 return aCallback.execute();
425 } catch (Exception e) {
426 // test case must fail.
428 throw new RuntimeException(e);
435 * Executes a transaction with a result, causing the testcase to fail if any
436 * type of exception is thrown.
439 * Code to be executed within the transaction.
441 public void executeTransaction(
442 final TestTransactionCallbackWithoutResult aCallback) {
443 executeTransaction(new TransactionCallbackWithoutResult() {
444 public void doInTransactionWithoutResult(TransactionStatus aArg) {
447 } catch (Exception e) {
448 // test case must fail.
449 throw new RuntimeException(e.getMessage(), e);
456 * Executes an SQL query.
460 * @return Result set.
462 public ResultSet executeQuery(String aSql) {
463 return executeQuery(aSql, new Object[0]);
467 * Executes a query with a single argument. See
468 * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
469 * supported argument types.
475 * @return Result set.
477 public ResultSet executeQuery(String aSql, Object aArg) {
478 return executeQuery(aSql, new Object[] { aArg });
482 * Executes a query. See
483 * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
484 * supported argument types.
489 * Arguments to the query.
490 * @return Result set.
492 public ResultSet executeQuery(final String aSql, final Object[] aArgs) {
494 Connection connection = getConnection();
496 PreparedStatement statement = connection.prepareStatement(aSql);
497 setPreparedParams(aArgs, statement);
499 return statement.executeQuery();
500 } catch (SQLException e) {
501 throw new RuntimeException(e);
506 * Sets the values of a prepared statement. See
507 * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
508 * supported argument types.
511 * Arguments to the prepared statement.
514 * @throws SQLException
516 private void setPreparedParams(final Object[] aArgs,
517 PreparedStatement aStatement) throws SQLException {
518 for (int i = 1; i <= aArgs.length; i++) {
519 setPreparedParam(i, aStatement, aArgs[i - 1]);
524 * Sets a prepared statement parameter.
527 * Index of the parameter.
529 * Prepared statement.
531 * Value Must be of type Integer, Long, or String. TODO extend
532 * with more types of values.
533 * @throws SQLException
535 private void setPreparedParam(int aIndex, PreparedStatement aStatement,
536 Object aObject) throws SQLException {
537 if (aObject instanceof Integer) {
538 aStatement.setInt(aIndex, ((Integer) aObject).intValue());
539 } else if (aObject instanceof Long) {
540 aStatement.setLong(aIndex, ((Integer) aObject).longValue());
541 } else if (aObject instanceof String) {
542 aStatement.setString(aIndex, (String) aObject);
544 TestCase.fail("Unsupported object type for prepared statement: "
545 + aObject.getClass() + " value: " + aObject
546 + " statement: " + aStatement);
550 private boolean isDatabaseConfigured() {
553 } catch (NoSuchBeanDefinitionException e) {
560 * @return Returns the dataSource.
562 public DataSource getDataSource() {
563 DataSource ds = (DriverManagerDataSource) getSpringContext().getBean(
571 * @throws SQLException
573 protected int getTableSize(final String aTable) throws SQLException {
575 ResultSet resultSet = executeQuery("select * from " + aTable);
578 while (resultSet.next()) {
584 protected int countResultSet(ResultSet aResultSet) throws SQLException {
587 while (aResultSet.next()) {