⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 howto.html

📁 dfdfddfskfjdsklfjksdljflksjfsjlkfdjlksfjkdsjfsdjkflsjkf
💻 HTML
📖 第 1 页 / 共 2 页
字号:
      to your database and        <a class="code">     getDataSet()   </a>        to return the dataset              you created in step 1.       </p>       <p>                 Following is a sample implementation that returns a connection to a Hypersonic              database and an xml dataset:                     <div id="source">      <pre>public class SampleTest extends DatabaseTestCase{    public SampleTest(String name)    {        super(name);    }    protected IDatabaseConnection getConnection() throws Exception    {        Class driverClass = Class.forName("org.hsqldb.jdbcDriver");        Connection jdbcConnection = DriverManager.getConnection(                "jdbc:hsqldb:sample", "sa", "");        return new DatabaseConnection(jdbcConnection);    }    protected IDataSet getDataSet() throws Exception    {        return new FlatXmlDataSet(new FileInputStream("dataset.xml"));    }}</pre>    </div>              </p>       <h4>           Step 3: (Optional) Implement getSetUpOperation() and getTearDownOperation()                methods       </h4>       <p>           By default, Dbunit performs a        <a href="components.html#cleanInsert">     CLEAN_INSERT   </a>               operation before executing each test and performs no cleanup operation                afterward. You can modify this behavior by overriding        <a class="code">     getSetUpOperation()   </a>               and        <a class="code">     getTearDownOperation()   </a>       .       </p>       <p>           The following example demonstrates how you can easily override the operation                executed before or after your test.                     <div id="source">      <pre>public class SampleTest extends DatabaseTestCase{    ...    protected DatabaseOperation getSetUpOperation() throws Exception    {        return DatabaseOperation.REFRESH;    }    protected DatabaseOperation getTearDownOperation() throws Exception    {        return DatabaseOperation.NONE;    }    ...}</pre>    </div>                    </p>       <h4>           Step 4: Implement your testXXX() methods       </h4>       <p>           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.       </p>       <a name="noextend">                                              <h3>           Database setup with your own TestCase subclass       </h3>                 </a>      <p>           In order to use Dbunit you are not required to extend the DatabaseTestCase              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.       </p>       <p>                 For example:                     <div id="source">      <pre>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;        // ...        try        {            DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);        }        finally        {            connection.close();        }    }    ...}</pre>    </div>      </p>       <a name="assertdata">                  <h3>           Database data verification       </h3>                 </a>      <p>           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.                     <div id="source">      <pre>public class Assertion{    public static void assertEquals(ITable expected, ITable actual)    public static void assertEquals(IDataSet expected, IDataSet actual)}</pre>    </div>      </p>       <h4>           Sample       </h4>       <p>           The following sample, show how to compare a database table snapshot                against a flat XML table.                     <div id="source">      <pre>public class SampleTest extends DatabaseTestCase{    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 FlatXmlDataSet(new File("expectedDataSet.xml"));        ITable expectedTable = expectedDataSet.getTable("TABLE_NAME");        // Assert actual database table match expected table        Assertion.assertEquals(expectedTable, expectedTable);    }}</pre>    </div>                    </p>       <p>           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.                      </p>       <p>           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.       </p>       <a name="assertquery">    <h4>           Using a query to take the database snapshot       </h4>   </a>      <p>           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.                     <div id="source">      <pre>        ITable actualJoinData = getConnection().createQueryTable("RESULT_NAME",                "SELECT * FROM TABLE1, TABLE2 WHERE ..."); </pre>    </div>                    </p>       <a name="compareignorecolumns">    <h4>           Ignoring some columns in comparison       </h4>   </a>      <p>           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.                <br>          </br>        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.               <div id="source">      <pre>            ITable filteredTable = DefaultColumnFilter.includedColumnsTable(actual,             expected.getTableMetaData().getColumns());    Assertion.assertEquals(expected, filteredTable); </pre>    </div>              </p>       <p>           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 colum        ns from both the expected and the actual table. See the FAQ about                <a href="faq.html#columnfilter">     excluding some table columns at runtime   </a>       .               </p>       <a name="roworder">    <h4>           Row ordering       </h4>   </a>      <p>           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        <code>           assertEquals       </code>                will fail.       </p>       <p>           You must order your database snapshot manually by using        <code>           IDatabaseConnection.createQueryTable       </code>                with an "ORDER BY" clause. Or you can use the        <code>           SortedTable       </code>                decorator class like this:                     <div id="source">      <pre>        Assertion.assertEquals(new SortedTable(expected),                new SortedTable(actual, expected.getTableMetaData()));</pre>    </div>      </p>       <a name="canoo">                  <h3>           DbUnit Ant task and Canoo WebTest       </h3>                 </a>      <p>           By Eric Pugh       </p>       <p>           With Dbunit Ant tasks, Dbunit makes it much easier to run Canoo WebTest                scripts for database centric applications.        <a href="http://webtest.canoo.com">     WebTest   </a>               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.                      </p>       <h4>           Step 1: Create your dataset file       </h4>       <p>           Your first step is to create your dataset file that you wan to load into              your database before running your WebTest script. Use one of the various              methods        <a href="#createdataset">     described above   </a>       . Put the various datasets you need in a        <code>           /data       </code>              directory.       </p>       <h4>           Step 2: Create your Ant build.xml file       </h4>       <p>           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:                     <ol>                          <li>                   <code>           test       </code>        : Runs all the testSuites that you have created                       </li>       <li>                   <code>           test:single       </code>        : Runs a single test in a specific testSuite                       </li>       <li>                   <code>           test:suite       </code>        : Runs all the tests for a specific testSuite                     </li>       </ol>       </p>       <h4>           Step 3: Create your various Test Suites       </h4>       <p>           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:                     <div id="source">      <pre>      &lt;target name="testSuite"&gt;        &lt;antcall target="unsubscribeEmailAddressWithEmail"/&gt;        &lt;antcall target="unsubscribeEmailAddressWithEmailID"/&gt;        &lt;antcall target="unsubscribeEmailAddressWithNewEmailAddress"/&gt;        &lt;antcall target="subscribeEmailAddressWithOptedOutEmail"/&gt;        &lt;antcall target="subscribeEmailAddressWithNewEmailAddress"/&gt;        &lt;antcall target="subscribeEmailAddressWithInvalidEmailAddress"/&gt;      &lt;/target&gt;</pre>    </div>      </p>       <p>           This way you can either run all the test's in your Test Suite, or just run              a specific one, all from build.xml!       </p>       <h4>           Step 4: Create your various Tests       </h4>       <p>           Now you need to write your various testcases. For more information on WebTest,              please refer to the        <a href="http://webtest.canoo.com">     WebTest home page   </a>       .              If you have find you are duplicating pieces of XML, then place them in a                     <code>           /includes       </code>         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.                     <div id="source">      <pre>      &lt;target name="subscribeEmailAddressWithOptedOutEmail"&gt;        &lt;dbunit            driver="${sql.jdbcdriver}"            url="${sql.url}"            userid="${sql.username}"            password="${sql.password}"&gt;                &lt;operation type="MSSQL_CLEAN_INSERT"                      src="data/subscribeEmailAddressWithOptedOutEmail.xml"                format="flat"/&gt;        &lt;/dbunit&gt;        &lt;testSpec name="subscribeEmailAddressWithOptedOutEmail"&gt;          &amp;amp;sharedConfiguration;          &lt;steps&gt;            &lt;invoke stepid="main page"              url="/edm/subscribe.asp?e=subscribeEmailAddressWithOptedOutEmail@test.com"              save="subscribeEmailAddressWithNewEmailAddress"/&gt;            &lt;verifytext stepid="Make sure we received the success message"              text="You have been subscribed to the mailing list"/&gt;          &lt;/steps&gt;        &lt;/testSpec&gt;      &lt;/target&gt;</pre>    </div>                    </p>       <h4>           Sample Directory Layout       </h4>       <p>           When you are done, you will have a series of files that look like this:                     <div id="source">      <pre>      \root\        build.xml        build.properties        TestSuiteEDM.xml        TestSuiteEDM.properties      \root\data\        subscribeEmailAddressWithOptedOutEmail.xml      \root\includes\        sharedConfiguration.xml</pre>    </div>      </p>       </div>                                                                                                            </div>              </div>            </td>          </tr>        </table>        <div id="footer">          <table border="0" style="width:100%" cellpadding="4" cellspacing="0">                        <tr>              <td>                                                                                                

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -