或者您可以使用XmlDataSet到位FlatXmlDataSet的,以避免問題「 - 」字符。下面你可以看到一個DbUnit的完整的例子:
package yourPackage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import org.dbunit.DBTestCase;
import org.dbunit.PropertiesBasedJdbcDatabaseTester;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.xml.XmlDataSet;
import org.junit.Test;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
public class TestDBUnitDummy extends DBTestCase
{
public TestDBUnitDummy(String name) throws Exception
{
super(name);
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, "com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, "jdbc:sqlserver://MyServer;databaseName=MyDatabase");
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, "sa");
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, "");
}
public static void Export() throws Exception
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection jdbcConnection = DriverManager.getConnection("jdbc:sqlserver://MySourceServer;databaseName=MyDatabase", "sa", "");
IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
QueryDataSet partialDataSet = new QueryDataSet(connection);
partialDataSet.addTable("TABLE-NAME", "SELECT * FROM [TABLE-NAME]");
XmlDataSet.write(partialDataSet, new FileOutputStream("table.xml"));
FlatXmlDataSet.write(partialDataSet, new FileOutputStream("table_flat.xml"));
}
protected void setUpDatabaseConfig(DatabaseConfig config)
{
config.setProperty(DatabaseConfig.PROPERTY_ESCAPE_PATTERN , "[?]");
}
protected IDataSet getDataSet() throws Exception
{
Export();
return new XmlDataSet(new FileInputStream("table.xml"));
}
@Test
public void test_001()
{
assertEquals("Dummy test", true, true);
}
}
[TABLE-NAME]與這些命令的SQL創建:
CREATE TABLE [TABLE-NAME](
[ID] [int] NULL,
[DESCRIPTION] [nvarchar](50) NULL
) ON [PRIMARY]
GO
INSERT INTO [TABLE-NAME] VALUES (1,'ONE')
INSERT INTO [TABLE-NAME] VALUES (2,'TWO')
INSERT INTO [TABLE-NAME] VALUES (3,'THREE')
GO
XmlDataSet看起來是這樣的:
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
<table name="TABLE-NAME">
<column>ID</column>
<column>DESCRIPTION</column>
<row>
<value>1</value>
<value>ONE</value>
</row>
<row>
<value>2</value>
<value>TWO</value>
</row>
<row>
<value>3</value>
<value>THREE</value>
</row>
</table>
</dataset>
FlatXmlDataSet外觀像這樣:
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
<[TABLE-NAME] ID="1" DESCRIPTION="ONE"/>
<[TABLE-NAME] ID="2" DESCRIPTION="TWO"/>
<[TABLE-NAME] ID="3" DESCRIPTION="THREE"/>
</dataset>
由於「 - 」字符,此xml文件格式不正確。