- 浏览: 187608 次
- 性别:
- 来自: 上海
文章分类
- 全部博客 (83)
- J2EE/Core Java (24)
- J2EE/Portal (2)
- J2EE/UI (4)
- J2EE/ATG (1)
- J2EE/Report (1)
- J2EE/Web Service/Rest API (2)
- Design Pattern (2)
- Arithmetic (4)
- Linux (12)
- Ruby&Rails (17)
- Database (5)
- J2EE/Payment (1)
- J2EE/JVM (1)
- Encryption/Decryption (3)
- J2EE/Multi Threading (4)
- SQL (1)
- https://community.teamviewer.com/t5/Knowledge-Base/Where-can-I-download-older-TeamViewer-versions-nbsp/ta-p/7729 (0)
最新评论
引用
Database testing
Unit tests for the database layer can be extremely valuable when building enterprise applications, but are often abandoned because of their complexity. Unitils greatly reduces this complexity, making database testing easy and maintainable. The following sections describe the support that the DatabaseModule and DbUnitModule have to offer for your database tests.
Unit tests for the database layer can be extremely valuable when building enterprise applications, but are often abandoned because of their complexity. Unitils greatly reduces this complexity, making database testing easy and maintainable. The following sections describe the support that the DatabaseModule and DbUnitModule have to offer for your database tests.
引用
We extend XLS dataset for this sample
Build Tool:maven
DB: Hsql
Spring jdbc
Build Tool:maven
DB: Hsql
Spring jdbc
1. maven dependency
<dependency> <groupId>org.unitils</groupId> <artifactId>unitils-io</artifactId> <version>3.3</version> </dependency> <dependency> <groupId>org.unitils</groupId> <artifactId>unitils-dbunit</artifactId> <version>3.3</version> <scope>test</scope> </dependency> <dependency> <groupId>org.unitils</groupId> <artifactId>unitils-spring</artifactId> <version>3.3</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.2-FINAL</version> <type>jar</type> <scope>compile</scope> </dependency>
2. Create unitils.properties in classpath.
database.driverClassName=org.hsqldb.jdbcDriver database.schemaNames=PUBLIC database.url=jdbc:hsqldb:mem:poc database.dialect=hsqldb database.userName=sa database.password= DbUnitModule.DataSet.loadStrategy.default=org.unitils.dbunit.datasetloadstrategy.impl.CleanInsertLoadStrategy DbUnitModule.DataSet.factory.default=com.wilson.unitils.MultiSchemaXlsDataSetFactory DbUnitModule.ExpectedDataSet.factory.default=com.wilson.unitils.MultiSchemaXlsDataSetFactory # The database maintainer is disabled by default. updateDataBaseSchema.enabled=true #This table is by default not created automatically dbMaintainer.autoCreateExecutedScriptsTable=true dbMaintainer.script.locations=src/test/resources/data #dbMaintainer.script.fileExtensions=sql,ddl #DbUnitModule.DataSet.loadStrategy.default=org.unitils.dbunit.datasetloadstrategy.impl.CleanInsertLoadStrategy #DatabaseModule.Transactional.value.default=commit # XSD generator dataSetStructureGenerator.xsd.dirName=resources/xsd
3. From the above configure, we can see MultiSchemaXlsDataSetReader and MultiSchemaXlsDataSetFactory are extended to support microsoft xls data set.
public class MultiSchemaXlsDataSetFactory implements DataSetFactory { protected String defaultSchemaName; public void init(Properties configuration, String defaultSchemaName) { this.defaultSchemaName = defaultSchemaName; } public MultiSchemaDataSet createDataSet(File... dataSetFiles) { try { MultiSchemaXlsDataSetReader xlsDataSetReader = new MultiSchemaXlsDataSetReader( defaultSchemaName); return xlsDataSetReader.readDataSetXls(dataSetFiles); } catch (Exception e) { throw new UnitilsException("创建数据集失败: " + Arrays.toString(dataSetFiles), e); } } public String getDataSetFileExtension() { return "xls"; } }
public class MultiSchemaXlsDataSetReader { private String defaultSchemaName; public MultiSchemaXlsDataSetReader(String defaultSchemaName) { this.defaultSchemaName = defaultSchemaName; } public MultiSchemaDataSet readDataSetXls(File... dataSetFiles) { try { Map<String, List<ITable>> tableMap = getTables(dataSetFiles); MultiSchemaDataSet dataSets = new MultiSchemaDataSet(); for (Entry<String, List<ITable>> entry : tableMap.entrySet()) { List<ITable> tables = entry.getValue(); try { DefaultDataSet ds = new DefaultDataSet(tables .toArray(new ITable[] {})); dataSets.setDataSetForSchema(entry.getKey(), ds); } catch (AmbiguousTableNameException e) { throw new UnitilsException("构造DataSet失败!", e); } } return dataSets; } catch (Exception e) { throw new UnitilsException("解析EXCEL文件出错", e); } } private Map<String, List<ITable>> getTables(File... dataSetFiles) { Pattern pattern = Pattern.compile("\\."); Map<String, List<ITable>> tableMap = new HashMap<String, List<ITable>>(); try { for (File file : dataSetFiles) { IDataSet dataSet = new XlsDataSet(new FileInputStream(file)); String[] tableNames = dataSet.getTableNames(); for (String each : tableNames) { String schema = null; String tableName; String[] temp = pattern.split(each); if (temp.length == 2) { schema = temp[0]; tableName = temp[1]; } else { schema = this.defaultSchemaName; tableName = each; } ITable table = dataSet.getTable(each); if (!tableMap.containsKey(schema)) { tableMap.put(schema, new ArrayList<ITable>()); } tableMap.get(schema).add(new XlsTable(tableName, table)); } } } catch (Exception e) { throw new UnitilsException("创建数据集失败: " + Arrays.toString(dataSetFiles), e); } return tableMap; } class XlsTable extends AbstractTable { private ITable delegate; private String tableName; public XlsTable(String tableName, ITable table) { this.delegate = table; this.tableName = tableName; } public int getRowCount() { return delegate.getRowCount(); } public ITableMetaData getTableMetaData() { ITableMetaData meta = delegate.getTableMetaData(); try { return new DefaultTableMetaData(tableName, meta.getColumns(), meta.getPrimaryKeys()); } catch (DataSetException e) { throw new UnitilsException("Don't get the meta info from " + meta, e); } } public Object getValue(int row, String column) throws DataSetException { Object delta = delegate.getValue(row, column); if (delta instanceof String) { if (StringUtils.isEmpty((String) delta)) { return null; } } return delta; } } }
4. in the above confire, we can also see following configure, this mean when unitils starts, it use the ddl under dbMaintainer.script.locations to initial the hsql table structure
dbMaintainer.script.locations=src/test/resources/data
We just create one table for testing
CREATE TABLE T_USER (USER_ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL PRIMARY KEY, USER_NAME VARCHAR(40) NOT NULL, PASSWORD VARCHAR(40) NOT NULL);
5. Our Unit test sample
package com.wilson.unitils; import org.junit.Assert; import org.junit.Test; import org.unitils.UnitilsJUnit4; import org.unitils.dbunit.annotation.DataSet; import org.unitils.spring.annotation.SpringApplicationContext; import org.unitils.spring.annotation.SpringBean; import com.wilson.dbunit.User; import com.wilson.dbunit.UserDao; @SpringApplicationContext("com/wilson/unitils/applicationContext.xml") public class UserDaoUnitilsTest extends UnitilsJUnit4{ @SpringBean("userDao") protected UserDao userDao; @Test @DataSet("UserDaoUnitilsTest_findUser.xls") public void findUser() throws Exception { User user = userDao.findUserByUserName("admin"); System.out.println(user); Assert.assertEquals("123456", user.getPassword()); } }
From the above code, we use import the data in UserDaoUnitilsTest_findUser.xls to hsql database, sheet name is table name, the first line is the column names
Database DDL:
CREATE TABLE T_USER (USER_ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL PRIMARY KEY, USER_NAME VARCHAR(40) NOT NULL, PASSWORD VARCHAR(40) NOT NULL);
another test case for validate db insert result. we need add annotion @ExpectedDataSet
@Test @ExpectedDataSet("UserDaoUnitilsTest_registerUser.xls") public void testRegisterUser() throws Exception { User user = new User(); user.setUserId(3); user.setUserName("user001"); user.setPassword("123456"); userDao.RegisterUser(user); }
The t_user table should has same content as the UserDaoUnitilsTest_registerUser.xls
6. if we want spring use the same datasource with unitils, we can add following as datasource in spring configure file.[repository\src\test\java\com\wilson\unitils\applicationContext.xml]
<bean id="dataSource" class="org.unitils.database.UnitilsDataSourceFactoryBean" />
Other code is related to spring jdbc and it's really simple , you can refer to the attachment. Be sure you have maven installed before running.
发表评论
-
Start tomcat with port 80 without Linux root user-Use iptables mapping
2016-05-25 17:39 832引用In linux system. only root us ... -
Format XML in JAVA
2016-01-11 12:23 605public static String format ... -
HttpURLConnection下载文件
2015-08-07 11:25 796public class HttpDownloadUtilit ... -
Ehcache RMI Replicated Cluster(RMI集群)
2013-04-25 23:39 1070引用本文是ehcache RMI集群的例子,导入附件中的jav ... -
JAXB入门
2012-10-16 11:59 789引用jaxb是一个读写xml的工具,还可以提供验证,不需要额外 ... -
Freemarker使用入门
2012-10-16 11:54 1021引用freemarker是一种模板标记工具,可以做页面静态化, ... -
perforce java api使用
2012-10-16 11:43 1256引用perforce是种版本管理软件,提供啦完整的java a ... -
XPath 入门
2012-10-16 11:29 882引用xpath可以快速定位获取XML文件中指定属性和值,jdk ... -
Java File Diff-diffutils
2012-09-27 17:35 74601. Maven Dependency <depende ... -
XSD 入门使用
2012-09-18 23:20 780<?xml version="1.0" ... -
nexus-2.1.1安装及使用入门
2012-08-13 22:52 14491. 安装 地址http://www.sonatype.org ... -
File Demo
2012-06-25 22:55 1312package org.springside.examples ... -
Java 访问sharepoint webservice(NTLM & SSL)
2012-06-12 09:47 3774引用遇到需要使用java访问微软的sharepoint的web ... -
Selenium Web Driver入门
2012-05-27 23:17 58401 What is Selenium? 引用Selenium ... -
HttpClient4.1.2 & HtmlUnit2.9 处理文件下载
2012-01-09 18:18 1029TestCode import java.io.Fi ... -
HttpClient4.1.2 & HtmlUnit2.9 NTLM 验证 和 Httpclient4.1.2 https/SSL
2012-01-09 18:13 15961. HttpClient4.1.2 & HtmlUn ... -
HttpClient4登陆ITeye
2012-01-08 23:33 1899import java.io.IOException; im ... -
Spring2集成测试
2011-08-25 22:21 764Spring2测试类继承层次 集成测试例子 public ... -
Learning EasyMock3.0 By Official Example
2011-08-24 16:48 1377Maven Installation+ add followi ... -
Maven+jetty+jrebel+m2eclipse+eclipse搭建struts2开发环境
2011-08-11 11:18 4127引用Maven:项目构建工具,通过pom.xml可以自动维护j ...
相关推荐
MySQL专家认证教材:Oracle Certified Professional: MySQL 5.6 Database Administrator
Database之Applied Mathematics for Database Professionals.pdf
In a single data structure, the GiST provides all the basic search tree logic required by a database system, thereby unifying disparate structures such as B+-trees and R-trees in a single piece of ...
MySQL认证官方教程:MySQL for Database Administrators Activity Guide
Oracle Database 12c Release 2 Testing Tools and Techniques for Performance and Scalability 英文azw3 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或...
UML for Database Design,UML for Database Design,UML for Database Design
A Framework for Testing Database Applications.pdf
Database Mathematcis
Welcome to “Beginning SQL for Oracle Database 18C”! Thanks for picking up this book. It’s safe to say you’re interested in learning about Oracle database, as that’s what this book is about. Why ...
Pro ODP.NET for Oracle Database 11g.pdf
Oracle官网的mysql培训学习指南,实验指南。是学习mysql不可多得的参考资料。
Oracle Database 11g Underground Advice for Database Administrators
Pro PowerShell for Database Developers helps you master PowerShell application development by continuing where other books leave off. There are no "Hello World" functions here, just real-world ...
Database Benchmarking and Stress Testing introduces you to database benchmarking using industry-standard test suites such as the TCP series of benchmarks, which are the same benchmarks that vendors ...
Pro Oracle Spatial for Oracle Database 11g shows how to take advantage of Oracle Database's built-in feature set for working with location-based data. A great deal of the information used in business ...
- UML for Database Design
关于Visual Studio 2005 Team Edition For Database Professional的好文章!
Data Preparation techniques for database