DbUnit使用简介

来源:互联网 发布:淘宝xylife海外专营店 编辑:程序博客网 时间:2024/06/08 19:11

前言:本篇博客是翻译自http://dbunit.sourceforge.net/howto.html,本人是一名初学者,而且并非专业人员,完全出于自我学习的兴趣,以及交流的目的,有任何疑问或者发现错误请及时提醒,万分感谢。

预备知识:简单的JDBC操作,java基本语法数据库的简单操作。

RDBMS即关系数据库管理系统(Relational Database Management System)

IDENTITY属性及自动增长,示例identity(1,1),表示这一列将自动从1开始编号,每插入一行,这一列就增1,并且插入数据时不能手动为这列插入,这列的值是系统自动插入的。

一、Database setup with a DBTestCase subclass

1.Create your dataset file(创建数据库的数据文件)

  Your test need some data to work with. This means you must create a dataset. In most situations you will work with xml datasets. You can manually create a flat XML dataset from scratch or create one by exporting some data from your database.

  我们进行数据库测试,测试数据是不可避免的,所以我们需要常见数据文件(dataset)。在大多数情况下我们通常使用的数据文件是XML格式。我们可以手动的创建一个flat XML dataset文件或者通过导出数据库中的数据来创建一个。

这里简单介绍一下XML dataset 与flat XML dataset:

flat XML dataset相对简介,表中的一行数据表示为:<表名称 字段名=值 ...../>

而XML dataset就相对繁琐了,同样是一行数据其表示为:

<表名称>

<字段名>值</字段名>

.....

</表名称>

1.1 通过数据库数据创建flat XML dataset格式的数据文件

手动创建再次简单说明一下:标准的XML文件头,全部内容包含在<dataset></dataset>标签中,内容格式参考上面说明。

官方提供的示例:

public class DatabaseExportSample{    public static void main(String[] args) throws Exception    {        // database connection        Class driverClass = Class.forName("org.hsqldb.jdbcDriver");        Connection jdbcConnection = DriverManager.getConnection(                                        "jdbc:hsqldb:sample", "sa", "");        IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);        // partial database export        QueryDataSet partialDataSet = new QueryDataSet(connection);        partialDataSet.addTable("FOO", "SELECT * FROM TABLE WHERE COL='VALUE'");        partialDataSet.addTable("BAR");        FlatXmlDataSet.write(partialDataSet, new FileOutputStream("partial.xml"));        // full database export        IDataSet fullDataSet = connection.createDataSet();        FlatXmlDataSet.write(fullDataSet, new FileOutputStream("full.xml"));        // dependent tables database export: export table X and all tables that        // have a PK which is a FK on X, in the right order for insertion        String[] depTableNames =            TablesDependencyHelper.getAllDependentTables( connection, "X" );        IDataSet depDataset = connection.createDataSet( depTableNames );        FlatXmlDataSet.write(depDataSet, new FileOutputStream("dependents.xml"));    }}
根据官方示例自己编写的测试文件:

工具:使用的是MySQL数据库。

public class Ceshi {public static void main(String[] args) throws Exception {// database connection 数据库链接Class.forName("com.mysql.jdbc.Driver");// 加载数据库驱动Connection jdbcConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/firpro", "root", "root");// 获取数据库链接IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);// 生成DbUnit的数据集的数据库链接// partial database export 部分数据导出QueryDataSet partialDataSet = new QueryDataSet(connection);partialDataSet.addTable("account","SELECT ID_ACCOUNT,ACCOUNT FROM ACCOUNT");partialDataSet.addTable("ac_ro");FlatXmlDataSet.write(partialDataSet,new FileOutputStream("partial.xml"));// full database export 整个数据库导出IDataSet fullDataSet = connection.createDataSet();FlatXmlDataSet.write(fullDataSet, new FileOutputStream("full.xml"));// dependent tables database export: export table X and all tables that// have a PK which is a FK on X, in the right order for insertion// 关联表的导出:需要按照插入的正确的顺序导出。例如X表的主键(PK)是其他表的外键(FK),换句话说X表是主表,其他表与其关联。String[] depTableNames = TablesDependencyHelper.getAllDependentTables(connection, "account");IDataSet depDataset = connection.createDataSet(depTableNames);FlatXmlDataSet.write(depDataset,new FileOutputStream("dependents.xml"));}}
测试结果:数据库中的数据成功导出。

将上面的细节进行更改,以及对生成文件的分析,发现了一些细节问题。

分析结果:

  1. 导出所有表所生成的文件,主表的数据在从表的下方。
  2. 导出部分表所生成的文件,主表与从表的数据位置与其执行partialDataSet.addTable()方法的顺序有关。
  3. 导出关联表所生成的文件,主表的数据在从表的上方。

这一结论也正好印证了我在《DbUnit数据库测试之备份与还原 》中的疑问,在那篇博客中我尝试的解决办法是关闭外键约束检查,不过在此看来是有点鸡肋了。

2.Extend a DBTestCase class

  Now you need to create a test class. One way to use Dbunit is to have the test class extend the DBTestCase class. DBTestCase extends the JUnit TestCase class. A template method is required to be implemented: getDataSet() to return the dataset you created in step 1. DBTestCase relies on a IDatabaseTester to do its work, the default configuration uses PropertiesBasedJdbcDatabaseTester, it locates configuration for the DriverManager within the Sytem properties. The simplest way to configure it would be in the constructor of your test class. You may modify this behavior by overriding getDatabaseTester(), using one of the other 3 provided IDatabaseTester implementations or your own.

  创建好测试数据文件了,接下来就是创建测试实例了。一种使用DbUnit的方式是继承DBTestCase这个类。DBTestCase继承了JUnit的TestCase类(这是JUnit3.x所具有的特性)。
继承了DBTestCase这个模板然后就必须对其进行实现了:

通过getDataSet()来返回一个你前面创建的测试数据文件相关联的dataset(个人理解:就是生成一个与测试数据文件相关的dataset)。DBTestCase依赖于IDatabaseTester,默认的配置使用的是PropertiesBasedJdbcDatabaseTester,其查找配置信息的位置是系统的配置文件(Sytem properties)。配置它的最简单的方法是在刚才创建的测试用例的构造函数中进行配置。你也可以通过覆盖并修改getDatabaseTester()来实现。

You may also use a subclass of DBTestCase(你也可以使用dbtestcase的子类), such as one of these:

JdbcBasedDBTestCaseuses a DriverManager to create connections (with the aid of a JdbcDatabaseTester).DataSourceBasedDBTestCaseuses a javax.sql.DataSource to create connections (with the aid of a DataSourceDatabaseTester).JndiBasedDBTestCaseuses a javax.sql.DataSource located through JNDI (with the aid of a JndiDatabaseTester).DefaultPrepAndExpectedTestCaseuses a configurable IDatabaseTester (allowing any connection type) with clear separation of prep and expected datasets.



















下面是一个示例实现,它返回一个数据库链接()和一个XML dataset:

public class SampleTest extends DBTestCase{    public SampleTest(String name)    {        super( name );        System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, "org.hsqldb.jdbcDriver" );        System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, "jdbc:hsqldb:sample" );        System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, "sa" );        System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, "" );// System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_SCHEMA, "" );    }    protected IDataSet getDataSet() throws Exception    {        return new FlatXmlDataSetBuilder().build(new FileInputStream("dataset.xml"));    }}

3.(Optional) Implement getSetUpOperation() and getTearDownOperation() methods

  默认情况下,DbUnit在每个测试前都会执行CLEAN_INSER(清除所有数据,并插入指定数据),但是每个测试结束后都没有清理操作,你可以通过重写getsetupoperation()和getteardownoperation()来进行修改。

下面的示例演示了如何可以很容易地重写在测试之前或之后执行的操作的方式。

public class SampleTest extends DBTestCase{    ...    protected DatabaseOperation getSetUpOperation() throws Exception    {        return DatabaseOperation.REFRESH;    }    protected DatabaseOperation getTearDownOperation() throws Exception    {        return DatabaseOperation.NONE;    }    ...}

4.(Optional) Override method setUpDatabaseConfig(DatabaseConfig config)

  使用这种方式可以更改一些DbUnit的配置信息。

下面的示例演示如何可以很容易地重写此方法:

public class SampleTest extends DBTestCase{    ...    /**     * Override method to set custom properties/features     */    protected void setUpDatabaseConfig(DatabaseConfig config) {        config.setProperty(DatabaseConfig.PROPERTY_BATCH_SIZE, new Integer(97));        config.setFeature(DatabaseConfig.FEATURE_BATCHED_STATEMENTS, true);    }    ...}

5.Implement your testXXX() methods

  Implement your test methods as you normally would with JUnit. Your database is now initialized before and cleaned-up after each test methods according to what you did in previous steps.

  和通常使用JUnit一样实现自己的测试方法。在以上的步骤中你已经对每次测试之前与之后数据库的初始化和清理进行了定义。

二、Database setup with your own TestCase subclass

  In order to use Dbunit you are not required to extend the DBTestCase class. You can override the standard JUnit setUp() method and execute the desired operation on your database. Do something similar in teardown() if you need to perform clean-up.

  为了使用DbUnit你没必要必须继承DBTestCase,你可以覆盖并重写JUnit的 setup()方法和执行对数据库的操作。如果需要清理工作也可以在teardown中进行。

public class SampleTest extends TestCase{    public SampleTest(String name)    {        super(name);    }    protected void setUp() throws Exception    {        super.setUp();        // initialize your database connection here        IDatabaseConnection connection = null;        // ...        // initialize your dataset here        IDataSet dataSet = null;        // ...        try1        {            DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);        }        finally        {            connection.close();        }    }    ...}
  Since version 2.2 you may use the new IDatabaseTester to accomplish the same feat. As explained in the previous topic, DBTestCase uses a IDatabaseTester internally to do its work; your test class may also use this feature to manipulate DataSets.

  从2.2版本之后,可以使用新的IDatabaseTester 来完成同样的工作了。在前面的讲述中,从2.2版本之后,可以使用新的IDatabaseTester 来完成同样的工作了。在前面的讲述中,DBTestCase使用IDatabaseTester来运行。你的测试类也可以使用这个特性来操作DataSets。
目前有4个方便的实现:DBTestCase使用IDatabaseTester来运行。你的测试类也可以使用这个特性来操作DataSets。
目前有4个方便的实现:

JdbcDatabaseTesteruses a DriverManager to create connections.PropertiesBasedJdbcDatabaseTesteralso uses DriverManager, but the configuration is taken from system properties.
This is the default implementation used by DBTestCase.DataSourceDatabaseTesteruses a javax.sql.DataSource to create connections.JndiDatabaseTesteruses a javax.sql.DataSource located through JNDI.













  You may also provide your own IDatabaseTester implementation. It is recommended to use AbstractDatabaseTester as a starting point. 

  您也可以提供您自己的idatabasetester实施。建议使用abstractdatabasetester为出发点。

public class SampleTest extends TestCase{    private IDatabaseTester databaseTester;    public SampleTest(String name)    {        super(name);    }    protected void setUp() throws Exception    {        databaseTester = new JdbcDatabaseTester("org.hsqldb.jdbcDriver",            "jdbc:hsqldb:sample", "sa", "");        // initialize your dataset here        IDataSet dataSet = null;        // ...        databaseTester.setDataSet( dataSet );// will call default setUpOperation        databaseTester.onSetup();    }    protected void tearDown() throws Exception    {// will call default tearDownOperation        databaseTester.onTearDown();    }    ...}

三、Database setup with no parent class

  In order to use Dbunit you are not required to extend any classes. Simply configure an instance of a DBTestCase subclass, whether directly instantiated or dependency injected in test classes.

  我们也可以不继承其它类,只需要实例化DBTestCase的一个子类或者直接实例化DBTestCase(或通过依赖注入)

下面示例使用PrepAndExpectedTestCase: (also see DefaultPrepAndExpectedTestCase JavaDoc).

public class SampleTest{    private PrepAndExpectedTestCase tc; // injected or instantiated, already configured        @Test    public void testExample() throws Exception    {        final String[] prepDataFiles = {}; // define prep files        final String[] expectedDataFiles = {}; // define expected files        final VerifyTableDefinition[] tables = {}; // define tables to verify        final PrepAndExpectedTestCaseSteps testSteps = () -> {            // execute test steps                return null; // or an object for use outside the Steps        };            tc.runTest(tables, prepDataFiles, expectedDataFiles, testSteps);    }}

四、Database data verification(数据库数据验证)

  Dbunit provides support for verifying whether two tables or datasets contain identical data. The following two methods can be used to verify if your database contains the expected data during test cases execution.

  DbUnit支持验证两个表或两个数据集(datasets)中的数据是否相同。下面是通过两种方法来验证数据库是否包含测试用例执行过程中的预期数据。

public class Assertion{    public static void assertEquals(ITable expected, ITable actual)    public static void assertEquals(IDataSet expected, IDataSet actual)}
  The following sample, show how to compare a database table snapshot against a flat XML table.
  下面这个示例展示的是如何将数据库中的表转换为一个flat XML dataset格式的表。

public class SampleTest extends DBTestCase{    public SampleTest(String name)    {        super(name);    }    // Implements required setup methods here    ...    public void testMe() throws Exception    {        // Execute the tested code that modify the database here        ...        // Fetch database data after executing your code        IDataSet databaseDataSet = getConnection().createDataSet();        ITable actualTable = databaseDataSet.getTable("TABLE_NAME");        // Load expected data from an XML dataset        IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(new File("expectedDataSet.xml"));        ITable expectedTable = expectedDataSet.getTable("TABLE_NAME");        // Assert actual database table match expected table        Assertion.assertEquals(expectedTable, actualTable);    }}
  The actual dataset is a database snapshot you want to verify against an expected dataset. As its name imply, the expected dataset contains the expectation values.

  实际的dataset(数据集)就是你想验证的期待的数据集的一个快照,就像名字暗示那样,期望的数据集包含期望的数据。

  The expected dataset must be different from the one you have used to setup your database. Therefore you need two datasets to do that; one to setup your database before a test and another to provide the expected data during the test.

  期待的数据集必须与你setup your database所使用的数据集不一样。因此你需要两个数据集来做这件事,一个用来在测试之前启动你的数据库,另一个提供在测试期间所期望的数据。

4.1 Using a query to take the database snapshot

  You can also verify if the result of a query match an expected set of data. The query can be used to select only a subset of a table or even join multiple tables together.

  我们也可以检查数据库查询结果来验证是否与期望的数据一致,并且我们可以查询表的部分数据,甚至多个表的关联数据来进行验证。

ITable actualJoinData = getConnection().createQueryTable("RESULT_NAME",                "SELECT * FROM TABLE1, TABLE2 WHERE ...");

4.2 Ignoring some columns in comparison

  Sometimes this is desirable to ignore some columns to perform the comparison; particularly for primary keys, date or time columns having values generated by the code under test. One way to do this is to omit to declare unwanted columns in your expected table. You can then filter the actual database table to only expose the expected table columns.

  有时候忽略一些字段(列)的进行比较是可取的;尤其是像主键、日期或时间的列在代码测试的过程中会有新的值生成。忽略这些字段的方法是在期待的表中声明不想测试的字段,我们可以过滤时机的数据库,只暴露预期的所有字段。

  The following code snippet shows you how to filter the actual table. To works, the actual table MUST contain at least ALL the columns from the expected table. Extra columns can exist in the actual table but not in the expected one.

  下面的代码片段战士李你如何过滤实际的表。为了正常运行实际的表中必须至少包含所有你所期望的字段。不期望的字段可以存在实际查询出来的表中,但是期待的数据对照表不能包含。(理所当然嘛,有点啰嗦了。)

 ITable filteredTable = DefaultColumnFilter.includedColumnsTable(actual,             expected.getTableMetaData().getColumns());    Assertion.assertEquals(expected, filteredTable);
A major limitation of this technique is that you cannot use a DTD with your expected flat XML dataset. With a DTD you need to filter columns from both the expected and the actual table. See the FAQ aboutexcluding some table columns at runtime

  这种方式的主要限制是你将不能使用DTD在你的flat XML dataset(flat XML数据集)。假如你要使用DTD,则你需要在预期的对照表,以及数据库查询的实际表中都将其过滤掉。(就是查询的时候把忽略的列排除掉)

4.3 Row ordering

  By default, database table snapshot taken by DbUnit are sorted by primary keys. If a table does not have a primary key or the primary key is automatically generated by your database, the rows ordering is not predictable and assertEquals will fail.

  默认情况下,数据库表的快照(映射)会根据主键进行排序。如果一个表没有主键或者主键由数据库自动生成,这些行的顺序是不确定的,因此会导致assertequal断言失败。

  You must order your database snapshot manually by using IDatabaseConnection.createQueryTable with an "ORDER BY" clause. Or you can use the SortedTable decorator class like this:

  在顺序不确定的情况下,我们必须使用IDatabaseConnection手动的对数据库的表的快照进行排序,及在查询时对查询进行排序,即使用"ORDER BY"命令。

或者我们可以使用SortedTable这个装饰类,如下:

Assertion.assertEquals(new SortedTable(expected),                new SortedTable(actual, expected.getTableMetaData()));      
  Note that the SortedTable uses the string value of each column for doing the sort by default. So if you are sorting a numeric column you notice that the sort order is like 1, 10, 11, 12, 2, 3, 4. If you want to use the columns datatype for sorting (to get the columns like 1, 2, 3, 4, 10, 11, 12) you can do this as follows:
  需要注意的是SortedTable默认使用的是每一个字段中的字符串的值来进行排序的。因此如果你整理的一个数字字段的排列顺序是1, 10, 11, 12, 2, 3, 4,你必须将其改为1, 2, 3, 4, 10, 11, 12这样排序才可以。

你可以像下面这样做:

SortedTable sortedTable1 = new SortedTable(table1, new String[]{"COLUMN1"});sortedTable1.setUseComparable(true); // must be invoked immediately after the constructorSortedTable sortedTable2 = new SortedTable(table2, new String[]{"COLUMN1"});sortedTable2.setUseComparable(true); // must be invoked immediately after the constructorAssertion.assertEquals(sortedTable1, sortedTable2);
  The reason why the parameter is currently not in the constructor is that the number of constructors needed for SortedTable would increase from 4 to 8 which is a lot. Discussion should go on about this feature on how to implement it the best way in the future.
  为什么当前的参数不在SortedTable构造器中的原因是构造函数的数量将增加从4到8。关于这个讨论我们应该考虑如何更好的去实现它(没理解)。

4.4 Assert and collect the differences

  By default, dbunit immediately fails when the first data difference was found. Starting with dbunit 2.4 it is possible to register a customFailureHandler which lets users specify which kinds of exceptions to be thrown and how to handle the occurrences of data differences. Using theDiffCollectingFailureHandler you can avoid an exception to be thrown on a data mismatch so that you can evaluate all results of the data comparison afterwards.

  默认情况下,DbUnit会在匹配到第一个数据差异时就停止,从2.4版本之后,可以通过注册一个定制的FailureHandler,这个FailureHandler允许用户指定那些类型的异常被抛出以及如何处理数据出现的差异。使用DiffCollectingFailureHandler我们可以避免在发生数据不匹配时抛出的异常,这样我们就可以评估所有数据比较之后的结果了。

IDataSet dataSet = getDataSet();DiffCollectingFailureHandler myHandler = new DiffCollectingFailureHandler();//invoke the assertion with the custom handlerassertion.assertEquals(dataSet.getTable("TEST_TABLE"),                       dataSet.getTable("TEST_TABLE_WITH_WRONG_VALUE"),                       myHandler);// Evaluate the results and throw an failure if you wishList diffList = myHandler.getDiffList();Difference diff = (Difference)diffList.get(0);...

五、Data File Loader

  Nearly all tests need to load data from one or more files, particularly for prep or expected data. dbUnit has a set of data file loader utility helper classes to load data sets from files on the classpath. The available loaders are in package org.dbunit.util.fileloader. A simple usage example:

  几乎所有测试都需要从一个或多个文件中加载数据,特别是预料或预期的数据。DbUnit有一组数据文件加载器使用工具通过classpath路径从文件中加载数据集。可以使用的加载器在org.dbunit.util.fileloader中。

下面是一个简单的使用用例:

DataFileLoader loader = new FlatXmlDataFileLoader();IDataSet ds = loader.load("/the/package/prepData.xml");
  Note the constructors for the various DataFileLoaders accept replacement object and replacement substring maps as used with ReplacementDataSet.

  需要注意的是这些各种各样的DataFileLoaders的构造器接受replacement object and replacement substring

  Refer to the DataFileLoader JavaDoc for further details. 更多细节可以参考DataFileLoader的JavaDoc

六、DbUnit Ant task and Canoo WebTest

  With Dbunit Ant tasks, Dbunit makes it much easier to run Canoo WebTest scripts for database centric applications.WebTest is a tool to simulate a user's browser clicking through the pages on a web site. It allows you to create a series of Ant based tests for your website. In fact, this can be used to perform User Acceptance tests for websites built using non Java technologies like ColdFusion or ASP! This document walks you through a suggested format for storing tests.

  使用Dbunit Ant tasks,DbUnit使其更容易运行Canoo WebTest的脚本在以数据库为中心的应用程序。WebTest是一个用来模拟用户访问的工具,其模拟的是用户的浏览器点击一个网站上的页面。其允许我们为我们自己的网站创建一系列基于Ant的测试。事实上,这可以用来为一些没有使用Java技术或者ASP的网站执行用户验收测试。

6.1 Create your dataset file

  Your first step is to create your dataset file that you want to load into your database before running your WebTest script. Use one of the various methods described above. Put the various datasets you need in a /data directory.

  第一步是在运行测试脚本之前创建你想加载的数据集的文件。使用上面描述的各种方法之一。把你需要的数据集放入到一个特定的文件中。

6.2 Create your Ant build.xml file

  A suggested setup is to have a single build.xml file that is the entry point for all your tests. This would include a couple targets like:

  建议使用一个独立的build.xml file文件来启动,而这个文件是所有测试的入口点。这将包含一些targets,如:

  1. test: Runs all the testSuites that you have created
  2. test:single: Runs a single test in a specific testSuite
  3. test:suite: Runs all the tests for a specific testSuite

6.3 Create your various Test Suites

  Once you have your build.xml file set up, you can now call the various TestSuites. Create a separate TestSuiteXXX.xml for the various modules that you would like to test. In your TestSuiteXXX.xml, you should have your default target testSuite call all the testcases you have definied:

  一旦你创建了build.xml,你就可以调用各种TestSuites了。为你想要测试的模块创建一个单独的TestSuiteXXX.xml,在TestSuiteXXX.xml中你应该有一个默认的target testSuite来调用所有的测试情况。

<target name="testSuite">        <antcall target="unsubscribeEmailAddressWithEmail"/>        <antcall target="unsubscribeEmailAddressWithEmailID"/>        <antcall target="unsubscribeEmailAddressWithNewEmailAddress"/>        <antcall target="subscribeEmailAddressWithOptedOutEmail"/>        <antcall target="subscribeEmailAddressWithNewEmailAddress"/>        <antcall target="subscribeEmailAddressWithInvalidEmailAddress"/></target>
  This way you can either run all the test's in your Test Suite, or just run a specific one, all from build.xml!
  你可以通过build.xml来运行所有的test用例,或者只运行特殊的一个。

6.4 Create your various Tests

  Now you need to write your various testcases. For more information on WebTest, please refer to theWebTest home page.If you have find you are duplicating pieces of XML, then place them in a /includes directory. If you have a single set of properties, then load them as part of build.xml by specifing them in your build.properties file. If you have multiple databases you need to connect to, then declare your sql connection properties in a TestSuiteXXX.properties file that you load on a per suite basis. In this example, we are using doing a clean insert into the database, and using the MSSQL_CLEAN_INSERT instead of CLEAN_INSERT because of the requirement to do identity column inserts.

  现在可以创建你所需要的测试用例了,

 <target name="subscribeEmailAddressWithOptedOutEmail">        <dbunit            driver="${sql.jdbcdriver}"            url="${sql.url}"            userid="${sql.username}"            password="${sql.password}">                <operation type="MSSQL_CLEAN_INSERT"                      src="data/subscribeEmailAddressWithOptedOutEmail.xml"                format="flat"/>        </dbunit>        <testSpec name="subscribeEmailAddressWithOptedOutEmail">          &sharedConfiguration;          <steps>            <invoke stepid="main page"              url="/edm/subscribe.asp?e=subscribeEmailAddressWithOptedOutEmail@test.com"              save="subscribeEmailAddressWithNewEmailAddress"/>            <verifytext stepid="Make sure we received the success message"              text="You have been subscribed to the mailing list"/>          </steps>        </testSpec> </target>

6. Sample Directory Layout

When you are done, you will have a series of files that look like this:

\root\  build.xml  build.properties  TestSuiteEDM.xml  TestSuiteEDM.properties\root\data\  subscribeEmailAddressWithOptedOutEmail.xml\root\includes\   sharedConfiguration.xml


*******DTD********How to generate a DTD representing my database schema?(不懂)

The following sample demonstrates how you can generate a flat xml dataset DTD from a database.

public class DatabaseExportSample{    public static void main(String[] args) throws Exception    {        // database connection        Class driverClass = Class.forName("org.hsqldb.jdbcDriver");        Connection jdbcConnection = DriverManager.getConnection("jdbc:hsqldb:sample", "sa", "");        IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);        // write DTD file        FlatDtdDataSet.write(connection.createDataSet(), new FileOutputStream("test.dtd"));    }}
Note that there is a more flexible possibility to write out a DTD which allows you to vary the content model of the DTD:
...        IDataSet dataSet = connection.createDataSet();        Writer out = new OutputStreamWriter(new FileOutputStream("myFile.dtd");        FlatDtdWriter datasetWriter = new FlatDtdWriter(out);        datasetWriter.setContentModel(FlatDtdWriter.CHOICE);        // You could also use the sequence model which is the default        // datasetWriter.setContentModel(FlatDtdWriter.SEQUENCE);        datasetWriter.write(dataSet);


最后修改时间:2016年10月11日15:07:00


********************************************************************************结束语********************************************************************************************
  我在写这篇博客的时候也是一名初学者,有任何疑问或问题请留言,或发邮件也可以,邮箱为:577328725@qq.com,我会尽早的进行更正及更改。
在我写过的博客中有两篇博客是对资源的整理,可能对大家都有帮助,大家有兴趣的话可以看看!!
下载资料整理——目录:http://blog.csdn.net/fanxiaobin577328725/article/details/51894331
  这篇博客里面是我关于我见到的感觉不错的好资源的整理,里面包含了书籍及源代码以及个人搜索的一些资源,如果有兴趣的可以看看,我会一直对其进行更新和添加。
优秀的文章&优秀的学习网站之收集手册:http://blog.csdn.net/fanxiaobin577328725/article/details/52753638
  这篇博客里面是我对于我读过的,并且感觉有意义的文章的收集整理,纯粹的个人爱好,大家感觉有兴趣的可以阅读一下,我也会时常的对其进行更新。
********************************************************************************感谢********************************************************************************************

0 0
原创粉丝点击