1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.oness.common.model.testing;
17
18 import java.io.File;
19
20 import javax.sql.DataSource;
21
22 import org.apache.commons.logging.Log;
23 import org.apache.commons.logging.LogFactory;
24 import org.dbunit.DatabaseTestCase;
25 import org.dbunit.database.DatabaseConnection;
26 import org.dbunit.database.IDatabaseConnection;
27 import org.dbunit.dataset.IDataSet;
28 import org.dbunit.dataset.excel.XlsDataSet;
29 import org.dbunit.dataset.xml.FlatXmlDataSet;
30
31 /***
32 * <p>
33 * DatabaseTestCase base class that uses Spring DataSource
34 * </p>
35 *
36 * @author Carlos Sanchez
37 * @version $Revision: 1.8 $
38 */
39 public abstract class SpringDatabaseTestCase extends DatabaseTestCase {
40
41 private static final String[] FILE_NAMES = { "dbunit.xml",
42 "src/test/dbunit.xml", "dbunit.xls", "src/test/dbunit.xls" };
43
44 private static Log log = LogFactory.getLog(SpringDatabaseTestCase.class);
45
46 public SpringDatabaseTestCase() {
47 super();
48 }
49
50 public SpringDatabaseTestCase(String name) {
51 super(name);
52 }
53
54 /***
55 * Gets connection from DataSource defined ApplicationContext with bean name
56 * "dataSource"
57 *
58 * @see org.dbunit.DatabaseTestCase#getConnection()
59 */
60 protected IDatabaseConnection getConnection() throws Exception {
61 DataSource dataSource = (DataSource) SpringApplicationContext
62 .getBean("dataSource");
63 return new DatabaseConnection(dataSource.getConnection());
64 }
65
66 /***
67 * Gets dataset from xml file "dbunit.xml" or "src/test/dbunit.xml", or xls
68 * files "dbunit.xls" or "src/test/dbunit.xls", the first that exists.
69 *
70 * @see org.dbunit.DatabaseTestCase#getDataSet()
71 */
72 protected IDataSet getDataSet() throws Exception {
73 File file = null;
74 for (int i = 0; i < FILE_NAMES.length; i++) {
75 file = new File(FILE_NAMES[i]);
76 if (file.exists()) {
77 if (log.isDebugEnabled())
78 log.debug("Using dataset from " + file);
79 break;
80 }
81 }
82 if (!file.exists()) {
83 if (log.isErrorEnabled())
84 log.error("No dataset file was found");
85 return null;
86 }
87 if (file.getName().endsWith(".xml"))
88 return new FlatXmlDataSet(file);
89 else if (file.getName().endsWith(".xls"))
90 return new XlsDataSet(file);
91
92
93 return null;
94 }
95 }