SQLUnit User Guide | ||
---|---|---|
<<< Previous | Next >>> |
The XML Tags that make up a SQLUnit test specification are described below.
The root tag for an SQLUnit test specification.
sqlunit ::= ((connection)+, (setup)*, (test | batchtest | diff | echo | func)+, (teardown)*) |
None. This is the top level element.
None
Table 1. Nested Elements for sqlunit
Name | Description | Required |
---|---|---|
connection | Specifies one or more database Connections that need to be instantiated for the test to run. | Yes, one or more. |
setup | Specifies any setup tasks that need to happen before all the tests in the suite are run. | No |
test | Specifies a test that needs to run in this suite. | Either one or more of test, batchtest, diff, echo or func |
batchtest | Specifies a test that uses the JDBC batching functionality. | Either one or more of test, batchtest, diff, echo or func |
diff | Specifies a test that compares the results generated by two SQL or stored procedure calls | Either one or more of test, batchtest, diff, echo or func |
echo | Echoes a string after substitution to the log. | Either one or more of test, batchtest, diff, echo or func |
func | Populates a single value returned from a stored procedure or SQL call into the SymbolTable, identified by function name | Either one or more of test, batchtest, diff, echo or func |
teardown | Specifies any tasks that need to happen after all the tests in the suite are run | No |
The setup tag specifies operations that need to be carried out once before all the tests defined in the XML file. Typical tasks may include dropping and recreating the test database and tables, or deleting and inserting test data into the tables. A setup operation can be specified either by zero or more nested sql tags or by zero or more nested include tag which specify an external file containing the setup SQL to execute. It can also contain set tags to setup variables to be used later for the test, or foreach tags which can be used to execute a single SQL multiple times, such as insert SQL statements.
setup ::= ((set)*, (((sql)*, (foreach)*) | (include)*)) |
None
Table 2. Nested Elements for setup
Name | Description | Required |
---|---|---|
set | Sets initial values for SQLUnit variables. | No |
funcdef | Defines a SQL or stored procedure call that can be used like a function call (single string result). | No |
subdef | Defines the structure of a SQL or stored procedure call. Values of parameters can be supplied or overriden in the actual sub call. | No |
sql | Specifies the SQL statement to be executed with or without replaceable parameters. | No |
foreach | Contains bulk SQL statements, such as inserts which are executed within the foreach tag. | No |
include | Specifies an external file which contains the SQL statements to execute during the setup phase. | No |
A simple setup to delete rows from a table
<setup> <sql><stmt>delete from foo where 1=1</stmt></sql> </setup> |
The skip tag is used to indicate to SQLUnit that this test should be skipped.
skip ::= (BODY) |
None
The struct tag is used to describe a user-defined data type (UDT) object returned as a STRUCT type. The UDT and Java Class must be specified in a typedef tag. The returned object is treated as a JavaBean, and the fields are the bean properties. Contained fields MUST be given in alphabetical order by name, case-insensitive.
struct ::= (field)* |
Table 5. Nested Elements for struct
Name | Description | Required |
---|---|---|
field | A field (bean property) of the returned object. | Zero or more |
Returning UDTs as STRUCTs.
<outparam id="1" type="STRUCT"> <struct> <field name="description">Red rubber ball</field> <field name="size">30</field> </struct> </outparam> |
The param tag is used to specify an argument to a SQL statement or stored procedure, or aggregated into a set of paramset tags for batch calls. The body of the tag contains the value of the parameter.
subparam ::= (BODY) |
Table 6. Attributes for subparam
Name | Description | Required |
---|---|---|
id | Specifies the sequence number of the parameter to be replaced. The sequence is one-based to keep parity with the JDBC specification. | Yes |
name | Specifies the name of the parameter to be replaced. This has been added for readability to help stored procedure authors/testers to spot errors quickly. | No |
type | Specifies the type of the parameter to be replaced. The type is a String, and has a one to one mapping to the datatypes defined in java.sql.Types. It also allows some additional Oracle specific types specified in net.sourceforge.sqlunit.OracleExtensionTypes. The value of the type is the same as the field name of the member variables in Types or OracleExtensionTypes classes. Thus if the type is Integer, the corresponding SQL type is java.sql.Type.INTEGER, and the string value that should be used here is INTEGER. | Yes |
is-null | If set to true, indicates that this parameter is an SQL NULL value. Valid values are true or false. | No, default is false. |
inout | Specifies whether the parameter is an IN, OUT or INOUT parameter. Valid values are in, out and inout respectively. | No, default is in. |
None
The batchresult element specifies the expected result from running either the statements specified in a batchsql or batchcall tag
batchresult ::= ((updatecount)*) |
Table 7. Attributes for batchresult
Name | Description | Required |
---|---|---|
expected-count | Specifies the number of rows expected to be updated as a result of executing the batchsql or batchcall element. If the expected-count is specified, then the number of updatecount elements will not be counted for determining the test's success | No |
failed-at | Specifies which statement in the batch is expected to fail when running the test. The index is zero-based | No |
A typical batchresult element
<batchresult> <updatecount>1</updatecount> <updatecount>1</updatecount> </batchresult> |
The call tag is used to describe a call to a stored procedure or function. A stored procedure differs from a standard SQL call in that it can return multiple result sets in a single result. Not all databases support this functionality in the same way. Stored procedures are called within Java code using the standard call syntax that looks like {call [?=]stored_procedure_name([?,...])}. This is also the way it should be specified to SQLUnit. SQLUnit uses the CallableStatement to execute this call
call ::= (stmt, (param)*) |
Table 10. Nested Elements for call
Name | Description | Required |
---|---|---|
stmt | Specifies the actual stored procedure call in JDBC format described above in the body of this element | Yes |
param | A param element specifies a single replaceable parameter specified for the stored procedure call. | Zero or more |
Call to Stored Procedure dept_id=AddDept(dept_name)
<call> <stmt>{? = call AddDept(?)}</stmt> <param id="1" type="INTEGER" inout="out">${deptId}</param> <param id="2" type="VARCHAR">Information Technology</param> </call> |
The set tag allows declarations of variable names and associating them with values within the context of a single SQLUnit run. SQLUnit stores these variables and their values in an internal symbol table. Variables need not be pre-declared in order to be used. A variable is usually created in the symbol table by being assigned the appropriate value based on context, the first time it is referenced in the XML file. Subsequent references to the variable will return the value of the variable.
set ::= ((sql|call),result)?|(constructoryArgs*,methodArgs*)? |
Table 11. Attributes for set
Name | Description | Required |
---|---|---|
name | Specifies the name of the SQLUnit variable. A variable must always be specified like ${varname}. Attempts to specify variables like varname or $varname will result in syntax error. | Yes |
value | Specifies the initial value of the variable. The value must be specified. In cases where you do not know the value, you can initialize it with a default value, or not invoke the set tag to declare the variable. When the variable is first encountered in SQLUnit, it will implicitly create an entry for that variable in the symbol table. | Not required if nested elements are specified. |
static | Specifies whether the method call is static. Valid values are true and false. | Required if the class and method attributes are also supplied |
class | Specifies the class name whose method has to be invoked to populate the variable | Only required if the method attribute is also supplied |
method | Specifies the method name in the specified class to invoke. | Only required if the class attribute is supplied |
Table 12. Nested Elements for set
Name | Description | Required |
---|---|---|
sql | Specifies a SQL statement to invoke which will populate the variables in the result. | Only required if there is no value attribute in the set tag. A call tag can also be specified here instead. |
call | Specifies a stored procedure call to invoke which will populate the variables in the result. | Only required if there is no value attribute in the set tag. A sql tag can also be specified instead. |
result | Specifies a result tag with variables in the col tag body. The variables will be populated from the values returned by the SQL or stored procedure call. | Only required if there is either a sql or a call tag. |
constructorArgs | Specifies arguments to a constructor of a non-static method if that is being used to populate the variable to set. | Only required if we want to invoke a non-static method |
methodArgs | Specifies arguments to the method to be executed to populate the variable to be set | Required if we want to invoke a method to set the variable |
Setting a variable ${var} to 14
<set name="${var}" value="14" /> |
Setting variable ${myquery.col1} from SQL
<set name="${myquery}"> <sql><stmt>select col1 from mytable where col2=45</stmt></sql> <result> <resultset id="1"> <row id="1"> <col id="1" name="c1" type="INTEGER">${col1}</col> </row> </resultset> </result> </set> |
Setting variable ${var} from a method call return
<set name="${var}" class="java.lang.System" static="true" method="getProperty"> <methodArgs> <arg name="key" type="java.lang.String" value="property" /> </methodArgs> </set> |
Provides the caller with the ability to classify and/or group tests by a given criteria. When the test is executed, the caller can pass to it some properties and the handler decides whether the test matches them. If the test matches it is executed, and if not, it is skipped and reported as skipped.
classifiers ::= ((severity)?, (category)?) |
None
None
An example of a classifiers tag
<test name="Find Agent by Id test" failure-message="Find Agent by Id test failed"> <classifiers> <severity>INFO</severity> <category>findById</category> </classifiers> <sql connection-id="mysql"> ... </sql> </test> |
A wrapper tag to group together JNDI properties that are needed to instantiate an InitialContext for the JNDI DataSource lookup.
jndi ::= ((arg)*) |
None
Table 13. Nested Elements for jndi
Name | Description | Required |
---|---|---|
arg | A tag that specifies the name and value of a single JNDI property. | One or more arg elements are required. |
A typical JNDI tag for getting a DataSource from JBoss
<connection> <datasource>jdbc/myDSN</datasource> <jndi> <arg name="java.naming.factory.initial" value="org.jnp.interfaces.NamingContextFactory" /> <arg name="java.naming.provider.url" value="jnlp://localhost:1099" /> <arg name="java.naming.factory.url.pkgs" value="org.jboss.naming" /> </jndi> </connection> |
The methodinvoker tag allows the caller to invoke methods in Java code and check to see if they complete without exception. These methods are generally, but need not be, JDBC specific. Any objects that are returned from the methods are ignored. The tag only verifies that the method ran successfully, and if not, it threw an expected exception.
methodinvoker ::= ((constructorArgs)*, (methodArgs)*) |
Table 14. Attributes for methodinvoker
Name | Description | Required |
---|---|---|
static | If set to true, specifies that the method being invoked is static. Valid values are true and false. | No, default is false. |
class | Specifies the full class name of the class in which the method is defined. | Yes |
method | Specifies the method name to invoke. | Yes |
Table 15. Nested Elements for methodinvoker
Name | Description | Required |
---|---|---|
constructorArgs | Wraps a set of arg elements which specify the arguments, if any, that the constructor will need. | Not required for static methods, or if the class has a default no-args constructor. |
methodArgs | Wraps a set of arg elements which specify the arguments, if any, that the method will need. | Not required if the method takes no arguments. |
A simple methodinvoker tag without method arguments
<methodinvoker class="net.sourceforge.sqlunit.utils.TestArgument" method="toString" > <constructorArgs> <arg name="c7" type="java.lang.Double.TYPE" value="0.2" /> </constructorArgs> </methodinvoker> |
The teardown tag specifies SQL operations that need to be carried out after all the tests in the XML file are done. If SQLUnit detects a test failure, it will skip the remaining tests and invoke the teardown operations before exiting. Typical tasks include dropping the test database or deleting data from test tables.
teardown ::= (((sql)*, (foreach)*) | (include)*) |
None
Table 16. Nested Elements for teardown
Name | Description | Required |
---|---|---|
sql | Specifies the SQL statements to be executed, with or without replaceable parameters, that should executed on teardown. | No |
foreach | Contains bulk SQL statements such as SQL DELETE statements, which will be executed from within a foreach tag. | No |
include | Specifies an external file which contains the SQL statements to be executed on teardown. | No |
Dropping some test tables on teardown
<teardown> <sql><stmt>drop table testdata</stmt></sql> <sql><stmt>drop table testdata2</stmt></sql> </teardown> |
The foreach tag allows for simple bulk substitution by replacing a named parameter in a SQL statement with values from a supplied list or values generated by incrementing a counter. The syntax is similar to FOR and FOREACH statements found in most programming languages.
foreach ::= ((sql)*) |
Table 17. Attributes for foreach
Name | Description | Required |
---|---|---|
param | The name of the parameter that will be substituted in the SQL statement. For example, if the param is id, then all occurences of ${id} will be substituted by the current value of id. | Yes |
values | A comma-separated list of values for the id. A value set can be specified within each element in the list. The elements of the set are separated with semi-colons. They are referred to later in the scope of the foreach tag as value_of_param.index. The index is 0-based. | No, either this or (start,stop,(step)) or (start,count,(step)) may be specified |
start | Specifies the starting value of the sequence of values for the param | No, values can be specified instead. If neither is specified, then start defaults to 0. |
stop | The ending value of the sequence of values for param | No, count can be specified instead. |
step | The increment if a sequence is specified with start and stop | No, defaults to 1. |
count | The number of entries in the sequence specified by start and stop. | No, stop can be specified instead. |
Table 18. Nested Elements for foreach
Name | Description | Required |
---|---|---|
sql | Contains a single SQL statement with placeholders for param which will be executed in a loop specified by the foreach attributes. The replaceable placeholder(s) should be specified as ${id}. | Yes |
A foreach used to prepare test data
<prepare> <sql><stmt>delete from foreachtest where 1=1</stmt></sql> <foreach param="id" start="0" stop="10" step="1"> <sql> <stmt>insert into foreachtest (id,name) values (${id},'name${id}')</stmt> </sql> </foreach> </prepare> |
Supplies information for the SQLUnit test harness to connect to the underlying database containing the stored procedures to be tested. Connections can be built using JDBC or from a DataSource object looked up through JNDI. Connections can also be specified using file URLs. Multiple connection tags can be specified if more than one Connection is needed for a single SQLUnit test suite.
connection ::= (((driver, url, user, password, (jarfile-url)?) | (datasource, jndi))?) |
Table 19. Attributes for connection
Name | Description | Required |
---|---|---|
connection-id | When multiple Connections are defined in a SQLUnit test, this attribute refers to a Connection to use for running this call by its connection-id. If not specified, SQLUnit will try to look up the default Connection which has no connection-id attribute defined. | No, default Connection is used if not supplied |
extern | If specified, the value of this attribute points to a Java properties file which contains the information necessary to build the Connection. The file can be specified without path information if it can be found in the caller's CLASSPATH or specified as a relative path, as well as an absolute path on the file system. A sample properties file can be found in /cvs/test/postgresql/sqlunit.properties. | No |
transaction-support | Indicates whether transaction support is provided by SQLUnit. Setting this to on (the default) will make SQLUnit treat each SQL or CALL as a single unit of work. Turning this to off will make SQLUnit not do any COMMITs or ROLLBACKs, it is left to the client to enforce boundaries of the unit of work by putting COMMIT and ROLLBACK in the SQL or stored procedures. Finally, turning this to implicit will put SQLUnit in auto commit mode, but SQLUnit will not do any explicit COMMIT or ROLLBACK. Transaction boundaries will either by enforced by the database if it supports it, or by the JDBC autocommit mechanism if not. | No, defaults to on |
reconnect-on-failure | Will destroy the current Connection and rebuild it in the event of a test failure or exception. This is needed to work around buggy database drivers which leave the Connection in an inconsistent state in such cases. | No, defaults to false |
server-name | If specified, will override the database server name that is derived from the DatabaseMetaData for the connection. This is used to lookup data types supported by this database. | No, defaults to the database server name |
Table 20. Nested Elements for connection
Name | Description | Required |
---|---|---|
driver | Specifies the full Java class name for the JDBC driver. This is needed for building the Connection using JDBC. | Yes (JDBC) |
url | Specifies the JDBC URL to the database | Yes (JDBC) |
user | Specifies the database user who will connect to the database | Yes (JDBC) |
password | Specifies the password for the database user | Yes (JDBC) |
jarfile-url | Specifies a URL (eg. file:///tmp/mydriver.jar) for a JAR file containing a JDBC driver which is not in the CLASSPATH. | No (JDBC) |
datasource | Specifies the name of a DataSource. By convention, this would look something like jdbc:/myDSN, where the DataSource object is actually stored under java:/comp/env/jdbc. This is likely to vary between JNDI servers and sites, so check with your administrator for the DataSource name to use | Yes (JNDI) |
jndi | Empty tag, contains zero or more arg elements containing the name-value pairs to pass in when creating the Initial Naming Context that will be used to look up the DataSource object. These name-value pairs locate the JNDI service. Each arg element will correspond to a line in the jndi.properties file for the given JNDI server. | Yes (JNDI) |
Specifying a JDBC connection for PostgreSQL
<connection> <driver>org.postgresql.Driver</driver> <url>jdbc:postgresql://localhost:5432/demodb</url> <user>defaultuser</user> <password>d3fau1tus3r</password> </connection> |
Specifying a JNDI connection with JBoss
<connection> <datasource>jdbc/myDSN</datasource> <jndi> <arg name="java.naming.factory.initial" value="org.jnp.interfaces.NamingContextFactory" /> <arg name="java.naming.provider.url" value="jnlp://localhost:1099" /> <arg name="java.naming.factory.url.pkgs" value="org.jboss.naming" /> </jndi> </connection> |
The func tag will replace the positional parameters in the SQL string defined in the corresponding funcdef tag, then run it and return a result.
func ::= (EMPTY) |
Table 21. Attributes for func
Name | Description | Required |
---|---|---|
name | The name of the func instance. The value returned from the execution of the func element will be available in the SymbolTable as ${func.name_of_func} for later tests in the same suite. | Yes |
lookup | The name of the funcdef element to look up. | Yes |
connection-id | The id of the connection to use, when multiple connections are defined. If not specified, it will use the default connection. | No |
param0-9 | The value for ${0}-${9} in the SQL string, if it exists. Note that if the variable is a string, you must supply the enclosing single quotes to indicate that. This type of query has no indication of the type of parameter being passed to it. | No |
id | The name or number of the sql call | No |
Table 22. Nested Elements for func
Name | Description | Required |
---|---|---|
skip | Indicates whether the func should be skipped or not. | No |
classifiers | Allows user to provide classification criteria for the func which SQLUnit can use to decide whether it should run the func or not based on criteria provided to match the classifier. | No |
Calling a definition without parameters
<func name="databasename" lookup="databasedef" /> |
Calling a custom function
<func name="mycol" lookup="customdef" param="234" /> |
Echoes the specified value to the log. This is mainly used for debugging a test.
echo ::= EMPTY |
Table 23. Attributes for echo
Name | Description | Required |
---|---|---|
name | A name for this echo tag | Yes, required by the SQLUnit logger |
text | The text to echo | Yes |
value | Specifies the expected value of text, if used in a test context. Saves caller the trouble of having to manually compare the expected and actual returned values. | no |
None
The include tag is used to specify an external file that contains a list of SQL statements that should be executed together. The statements can be separated from one another by a free standing slash (/) or semi-colon character (;) on its own line, or by a line terminated by a semi-colon (;) character.
include ::= (EMPTY) |
Table 24. Attributes for include
Name | Description | Required |
---|---|---|
file | Specifies a relative or absolute path name to the file containing the SQL statements. | Yes |
connection-id | When multiple Connections are defined in a SQLUnit test, this attribute is used to select the Connection to use for running the SQL statements. If not specified, SQLUnit will use the default Connection if that is specified. | No |
None
Cleanup SQL being included in a teardown tag
<teardown> <include file="test/sybase/teardown.sql" /> </teardown> |
The result tag allows the test author to specify an expected result from a SQL call or stored procedure. SQLUnit executes the SQL or stored procedure and converts the results into an internal Result object. It will also convert the data supplied in the result tag to an internal Result object, and then compares the two for equality. Values specified in the col nested element of a result element can contain variable names instead of literal values. The variable names will be updated with the values from the internal symbol table. Result tags can also contain an exception element if the call is expected to throw an exception for this particular test. Note that all id attributes of the result and its nested elements start at 1, so as to be consistent with how JDBC resultsets are set up, and minimize confusion between the two representations.
result ::= ((((outparam)*, (updatecount)?, (resultset)*)+ | ((outparam)*, exception))?) |
Table 25. Attributes for result
Name | Description | Required |
---|---|---|
id | The id of the result | No |
echo | If set to true, the result will be echoed to the output. The test will be short-circuited and SQLUnit will not attempt to do any matching. This is useful for debugging. Valid values are true and false. | No, defaults to false |
Table 26. Nested Elements for result
Name | Description | Required |
---|---|---|
outparam | Zero or more outparam elements may be specified, each representing an output parameter from the stored procedure. An outparam element can contain a resultset element in case of Oracle CURSOR types, or text information in case of non-CURSOR types. | No |
updatecount | Specifies the updatecount that is returned from the SQL or stored procedure call. | No. |
resultset | The resultset tag specifies a single resultset returned from a database call (SQL or stored procedure). A result element can contain one or more resultsets, which in turn will contain one or more rows, which would contain one or more columns. If there are no rows, a resultset can also be empty. | No. |
exception | The exception tag is used to test for expected failures of a stored procedure in response to specific inputs. | No. Exception tags can coexist with outparam tags. |
A multi-resultset result tag
<result> <resultset id="1"> <row id="1"> <col id="1" name="c1" type="INTEGER">1</col> <col id="2" name="c2" type="VARCHAR">Blah</col> <col id="3" name="c3" type="INTEGER">3</col> </row> </resultset> <resultset id="2" /> <resultset id="3" /> <resultset id="4"> <row id="1"> <col id="1" name="ac1" type="INTEGER">1</col> <col id="2" name="ac2" type="INTEGER">1</col> <col id="3" name="ac3" type="VARCHAR">Unused Blahs</col> <col id="4" name="ac4" type="INTEGER">1</col> <col id="5" name="ac5" type="VARCHAR">Unused</col> </row> <row id="2"> <col id="1" name="ac1" type="INTEGER">1</col> <col id="2" name="ac2" type="INTEGER">1000</col> <col id="3" name="ac3" type="VARCHAR">Deprecated Blahs</col> <col id="4" name="ac4" type="INTEGER">1</col> <col id="5" name="ac5" type="VARCHAR">Deprecated</col> </row> </resultset> </result> |
A result containing an exception
<result> <exception> <code>1234</code> <message>Test Exception</message> </exception> </result> |
A wrapper tag to group together arguments to a method call.
methodArgs ::= ((arg)*) |
None
Table 27. Nested Elements for methodArgs
Name | Description | Required |
---|---|---|
arg | A tag that specifies the name, type and value of the method argument. | One or more arg elements are required. |
A methodArgs tag with different argument types
<methodArgs> <arg name="m3" type="java.lang.Integer" value="-2147483648" /> <arg name="m7" type="java.lang.Double" value="2.2" /> <arg name="m8" type="java.lang.String" value="Some text" /> </methodArgs> |
Represents a row in a database table returned from a SQL or stored procedure call.
row ::= (col)+ |
Table 29. Nested Elements for row
Name | Description | Required |
---|---|---|
col | A row can have one or more col elements defined within it. | Yes |
The param tag is used to specify an argument to a SQL statement or stored procedure, or aggregated into a set of paramset tags for batch calls. The body of the tag contains the value of the parameter.
param ::= (BODY) |
Table 30. Attributes for param
Name | Description | Required |
---|---|---|
id | Specifies the sequence number of the parameter to be replaced. The sequence is one-based to keep parity with the JDBC specification. | Yes |
name | Specifies the name of the parameter to be replaced. This has been added for readability to help stored procedure authors/testers to spot errors quickly. | No |
type | Specifies the type of the parameter to be replaced. The type is a String, and has a one to one mapping to the datatypes defined in java.sql.Types. It also allows some additional Oracle specific types specified in net.sourceforge.sqlunit.OracleExtensionTypes. The value of the type is the same as the field name of the member variables in Types or OracleExtensionTypes classes. Thus if the type is Integer, the corresponding SQL type is java.sql.Type.INTEGER, and the string value that should be used here is INTEGER. | Yes |
scale | Specifies the scale of the parameter value if the value maps to a BigDecimalType. This is an optional parameter. SQLUnit will try its best to guess the scale based on the actual value, but this is useful if the value cannot be specified or is NULL. | No |
typename | Specifies the name of a user-defined type. This is an optional parameter. | No |
is-null | If set to true, indicates that this parameter is an SQL NULL value. Valid values are true or false. | No, default is false. |
inout | Specifies whether the parameter is an IN, OUT or INOUT parameter. Valid values are in, out and inout respectively. | No, default is in. |
None
funcdef ::= |
Table 31. Attributes for funcdef
Name | Description | Required |
---|---|---|
name | The name of the function definition. This will be used to call the definition from the func tag. | Yes |
query | The SQL query with numbered replaceable parameters (see example below) which will be called to return the result. | Yes |
description | User Documentation for the function definition. | No |
None
Defining call to MySQL built-in function
<funcdef name="databasedef" query="select DATABASE()" description="Returns the current database name" /> |
Defining call to a custom function
<funcdef name="customdef" query="select myCol from myTable where myCol1 = ${0}" description="Defines a custom function" /> |
The batchsql tag allows the client to specify a set of non-parameterized SQL statements which need to run in a batch. SQLUnit uses the JDBC batching mechanism to run the set of SQL statements.
batchsql ::= ((stmt)+) |
Table 32. Attributes for batchsql
Name | Description | Required |
---|---|---|
connection-id | When multiple Connections are defined in a SQLUnit test, this attribute provides a mechanism for choosing one of the defined Connections to use for running this batch. If a connection-id is not specified, SQLUnit will try to look up a Connection which has no connection-id. | No |
A typical batchsql call
<batchsql> <stmt>delete from customer where custId=1</stmt> <stmt>insert into customer values(1,'Some One','secret', 'en_US',null,0,now())</stmt> <stmt>insert into customer values(1,'Someone Else','secret', 'en_US',null,0,now())</stmt> <stmt>delete from customer where 1=1</stmt> </batchsql> |
The prepare tag specifies additional SQL statements that should be run before the test in whose block it appears in. This is used for specifying additional operations that need to happen on a per-test basis, which is not covered in the setup tag.
prepare ::= ((set)*, (sql)*, (foreach)*) |
None
Table 34. Nested Elements for prepare
Name | Description | Required |
---|---|---|
set | This tag sets values for SQLUnit test variables into the SQLUnit symbol table. | No. |
sql | Identifies one or more SQL statements that should be executed as part of the per-test prepare | No. |
foreach | Specifies a block within a foreach block which is executed as part of the prepare. | No. |
A foreach tag inside a prepare tag
<prepare> <sql><stmt>delete from foreachtest where 1=1</stmt></sql> <foreach param="id" start="0" stop="10" step="1"> <sql><stmt>insert into foreachtest (id,name) values (${id},'name${id}')</stmt></sql> </foreach> </prepare> |
The typedef tag defines a UTD type name and corresponding Java class name.
typedef ::= (EMPTY) |
None
Defining UTD-Java class mappings.
<typemap> <typedef typename="MY_SQL_OBJ" classname="org.my.stuff.MyClass" /> <typedef typename="THEIR_SQL_OBJ" classname="org.their.things.TheirClass" /> </typemap> |
Allows caller to define various levels of Severity for a test. Valid values are FATAL, ERROR, WARN, INFO and DEBUG.
severity ::= (BODY) |
None
None
Wrapper tag for one or more param elements.
paramset ::= ((param)+) |
Table 37. Nested Elements for paramset
Name | Description | Required |
---|---|---|
param | Specifies argument names and values to be passed into a batchcall call. | One or more |
A paramset passed into an INSERT batchcall
<paramset id="1"> <param id="1" type="INTEGER">1</param> <param id="2" type="VARCHAR">Some One</param> </paramset> |
The subdef tag is used to define a stored procedure or SQL call. All parameters need to be defined, but some parameters may not have values associated with them. These are plugged in when the actual call is made using the sub tag. This allows test writers to save keystrokes and work at a higher level of abstraction than building the tests manually with stored procedures or SQL calls each time.
subdef ::= ((param)*) |
Table 38. Attributes for subdef
Name | Description | Required |
---|---|---|
name | The name of the subroutine definition. This will be used by the sub tag to specify the definition to look up. | Yes |
query | The SQL or stored procedure call with replaceable parameters specified as in the sql or call tags. | Yes |
description | A user-friendly description of the subroutine definition. Used for documentation | No |
type | Specifies whether to treat the SQL as a stored procedure or SQL call when called. Valid values are sql and call. | No, defaults to sql |
Table 39. Nested Elements for subdef
Name | Description | Required |
---|---|---|
param | Specifies zero or more parameters that are supplied with the subroutine definition. All parameters that the call requires should be supplied, although some or all the values may remain unspecified. Unspecified values are denoted with a single '?' character in the text of the param element. | Zero or more parameters can be specified |
A sample subroutine definition
<subdef name="UpsertStreetDef" query="{? = pk_edit_street.upsert_street(?,?)}" description="Definition of Upsert Street"> <param id="1" type="INTEGER" name="rc" inout="out"> {t} ${streetId} </param> <param id="2" type="VARCHAR" name="street">?</param> <param id="3" type="VARCHAR" name="city">SFO</param> </subdef> |
Represents a column of a database table returned from a SQL or stored procedure call.
col ::= (BODY) |
None
The batchtest tag allows specifying a batch of SQL statements or stored procedure calls that must be executed within a batch. It allows the client to specify the expected number of results, and a point where a failure may be expected. Note that only statements which update data in some way should be specified hre, since the JDBC specification does not allow the returning of resultsets from SQL statements run using the batching feature
batchtest ::= ((skip)?, (classifiers)?, (batchcall | batchsql), batchresult) |
Table 41. Attributes for batchtest
Name | Description | Required |
---|---|---|
name | The name of the batch test. THis is used by SQLUnit to print progress messages to its log output | Yes |
assert | Specifies a single or comma-separated assertion that must hold true for the batch test. | No, defaults to equal if not specified. |
failure-message | If specified, SQLUnit will print the user-supplied failure message if the test failed | No, default is no failure message |
java-object-support | If set to true, Java Object Support is enabled for the test | No, default is false |
Table 42. Nested Elements for batchtest
Name | Description | Required |
---|---|---|
skip | Indicates whether the func should be skipped or not. | No |
classifiers | Allows user to provide classification criteria for the func which SQLUnit can use to decide whether it should run the func or not based on criteria provided to match the classifier. | No |
batchcall | Specifies the set of batch calls to be made. Either batchcall or batchsql must be specified | No, but see Description |
batchsql | Specifies the set of batch calls to be made. Either batchcall or batchsql must be specified | No, but see Description |
batchresult | Specifies the expected return values from the call | Yes |
A typical batchtest specification
<batchtest name="Testing basic batchtest functionality"> <batchsql> <stmt>delete from customer where custId=1</stmt> <stmt>insert into customer values(1,'Some One','secret', 'en_US',null,0,now())</stmt> <stmt>insert into customer values(1,'Someone Else','secret', 'en_US',null,0,now())</stmt> <stmt>delete from customer where 1=1</stmt> </batchsql> <batchresult> <updatecount>1</updatecount> <updatecount>1</updatecount> <updatecount>1</updatecount> <updatecount>2</updatecount> </batchresult> </batchtest> |
Collection of arg elements that need to be passed to the constructor of a specified class whose method needs to be invoked by SQLUnit
constructorArgs ::= ((arg)*) |
None
Table 43. Nested Elements for constructorArgs
Name | Description | Required |
---|---|---|
arg | Specifies an individual argument | One or more |
Example of a constructorArgs tag
<constructorArgs> <arg name="c1" type="java.lang.Byte" value="-128" /> <arg name="c2" type="java.lang.Short" value="-32768" /> <arg name="c3" type="java.lang.Integer" value="-2147483648" /> <arg name="c5" type="java.lang.Character" value="a" /> <arg name="c6" type="java.lang.Float" value="1.1" /> <arg name="c7" type="java.lang.Double" value="2.2" /> <arg name="c8" type="java.lang.String" value="Some text" /> </constructorArgs> |
The batchcall tag allows the SQLUnit client to run a single stored procedure or parameterized SQL with a set of different input arguments. It uses JDBC batching to do this.
batchcall ::= ((stmt), (paramset)+) |
Table 44. Attributes for batchcall
Name | Description | Required |
---|---|---|
connection-id | When multiple Connections are defined for a SQLUnit test, this attribute refers to the Connection to use for running this call. If not specified, SQLUnit will try to look up a Connection which has no connection-id attribute specified. | No |
Table 45. Nested Elements for batchcall
Name | Description | Required |
---|---|---|
stmt | Contains the SQL statement or stored procedure to call in the body. | Yes |
param | Specifies a set of param elements | At least one needs to be provided |
A typical batchcall tag
<batchcall> <stmt>insert into customer values(?,?,?,?,?,?,now())</stmt> <paramset id="1"> <param id="1" type="INTEGER">1</param> <param id="2" type="VARCHAR">Some One</param> <param id="3" type="VARCHAR">secret</param> <param id="4" type="VARCHAR">en_US</param> <param id="5" type="VARCHAR">SQLUnit</param> <param id="6" type="INTEGER">0</param> </paramset> <paramset id="2"> <param id="1" type="INTEGER">2</param> <param id="2" type="VARCHAR">Someone Else</param> <param id="3" type="VARCHAR">secret</param> <param id="4" type="VARCHAR">en_US</param> <param id="5" type="VARCHAR">SQLUnit</param> <param id="6" type="INTEGER">0</param> </paramset> </batchcall> |
The outparam tag is used to represent OUT parameters returned as a result of a Stored procedure call. The value is stored in the body text as a String or as a embedded resultset element in case of CURSOR type OUT parameters.
outparam ::= (BODY)|(resultset)|(struct) |
Table 47. Nested Elements for outparam
Name | Description | Required |
---|---|---|
resultset | This is needed only when the type of the OUT parameter is a CURSOR, and specifies the value of the CURSOR outparam. | Not if the type is not CURSOR |
A outparam with a INTEGER value
<outparam id="1" type="INTEGER">24</outparam> |
A outparam tag with an embedded CURSOR
<outparam id="1" type="oracle.CURSOR"> <resultset id="1"> <row id="1"> <col id="1" type="INTEGER">7</col> <col id="2" type="VARCHAR">James Bond</col> <col id="3" type="VARCHAR">Martini</col> </row> </resultset> </outparam> |
The typemap tag defines mappings of user-defined data types (UDTs) to their corresponding Java classes. These mappings are required for handling all STRUCT type values in the tests that use this connection. This includes nested UDT objects.
typemap ::= (typedef)* |
None
Table 48. Nested Elements for typemap
Name | Description | Required |
---|---|---|
typedef | A UTD type name and corresponding Java class name. | Zero or more |
Defining mappings from UTDs to Java classes.
<connection> <typemap> <typedef typename="MY_SQL_OBJ" classname="org.my.stuff.MyClass" /> </typemap> </connection> |
The test tag specifies the SQL statement or stored procedure that needs to be tested, its input parameters, and the expected output. The tag will be run by SQLUnit to compare the expected results against the actual result.
test ::= ((skip)?, (classifiers)?, (match)*, (prepare)?, ((sql | call | methodinvoker | dynamicsql), result)?) |
Table 49. Attributes for test
Name | Description | Required |
---|---|---|
name | Specifies a human-readable name for the test, which will be printed to the log as part of SQLUnit's progress messages. | Yes |
assert | Specifies a single or comma-separated list of assertions that must be true for the test. | No, defaults to equal |
failure-message | Allows the caller to supply an error message which should be displayed if the test failed. | No, if not specified, no user message will be displayed. |
java-object-support | If set to on, indicates that Java Object Support is turned on. Valid values are on and off. | No, default is off |
expected-duration-millis | If specified, specifies that SQLUnit should time the test and fail the test if the test does not complete in the window specified +/- a percentage tolerance if specified, or 10% if not. | No |
percentage-tolerance | If specified with expected-duration-millis, this specifies the percentage tolerance that SQLUnit will put on the expected-duration in order to calculate if the test should fail. | No, will default to 10 if expected-duration-millis is specified and percentage-tolerance is not specified. |
Table 50. Nested Elements for test
Name | Description | Required |
---|---|---|
skip | Indicates whether the test should be skipped or not. | No |
classifiers | Allows user to provide classification criteria for the test which SQLUnit can use to decide whether it should run the test or not based on criteria provided to match the classifier. | No |
match | Specifies zero or match elements that should be applied to match the result returned with that specified. | No |
prepare | Specifies SQL setup code that must be run on a per-test basis. | No |
sql | Specifies the SQL statement that must be run for this test. | Either one of sql, call, methodinvoker, dynamicsql or sub |
call | Specifies a stored procedure that must be run for the test. | Either one of sql, call, methodinvoker, dynamicsql or sub |
methodinvoker | Specifies a method that should be invoked for the test. | Either one of sql, call, methodinvoker, dynamicsql or sub |
dynamicsql | Specifies a method which returns a String of dynamic SQL code that should be executed for this test. | Either one of sql, call, methodinvoker, dynamicsql or sub |
sub | Specifies a predefined and partially specified named SQL or stored procedure call | Either one of sql, call, methodinvoker, dynamicsql or sub func is required. |
result | Specifies the expected result from the test. | Yes |
<test name="Adding department HR"> <sql> <stmt>select AddDept(?)</stmt> <param id="1" type="VARCHAR">Human Resources</param> </sql> <result> <resultset id="1"> <row id="1"> <col id="1" name="adddept" type="INTEGER"> ${deptId_HR} </col> </row> </resultset> </result> </test> |
Represents a resultset returned from a SQL or stored procedure call.
resultset ::= (row)* |
Table 51. Attributes for resultset
Name | Description | Required |
---|---|---|
id | The resultset id | Yes |
partial | If set to true, indicates that rows are partially specified. Valid values are true and false. Rows will be matched based on the row's id attribute. | No, defaults to false |
rowcount | Specifies the number of rows in the resultset. This is specified when the test client wants SQLUnit to only match the number of rows in the resultset, rather than the contents themselves. | No |
order-by | A comma-separated list of column ids on which the rows in the resultset should be sorted. By default, both the resultset returned from the SQL or stored procedure call and the resultset that is specified will be sorted before comparing. The default sorting is by all the specified columns in the order in which they appear. The order-by attribute should be used only if the default sort needs to be overriden, for example, when the SQL or stored procedure returns ordered data. The sort order specified is ASCENDING, unless the column id is prefixed with a negative sign, which will cause it to be sorted in DESCENDING order. Setting order-by to NONE will turn off auto-sorting. | No |
Table 52. Nested Elements for resultset
Name | Description | Required |
---|---|---|
row | A resultset can have zero or more row elements | No |
A simple resultset tag containing a single row
<resultset id="1"> <row id="1"> <col id="1" name="col1" type="INTEGER">1</col> </row> </resultset> |
The match tag specifies a user-defined matching strategy that will be applied instead of the default strategy to check for exact equality between two column values
match ::= ((arg)*) |
Table 53. Attributes for match
Name | Description | Required |
---|---|---|
resultset-id | If specified, defines the resultset(s) on which the user- defined matching criteria should be applied. Wildcards may be applied to specify multiple values using a '*', eg. '3*' or '*'. Ranges may be specified using an expression such as '1-2', or enumerations using an expression of the form '1,2,3'. | No, defaults to all resultsets if not specified |
row-id | If specified, defines the row(s) on which the user-defined matching strategy will be applied. Same wildcarding rules as defined in resultset-id apply. | No, defaults to all if not specified |
col-id | If specified, defines the column(s) on which the user-defined matching strategy should be applied. Same wildcarding rules as defined in resultset-id apply. | No, defaults to all if not specified |
matcher | The full class name of the Matcher class that will be used for the user-defined matching. The Matcher class must implement the IMatcher interface and be available in the caller's CLASSPATH | Yes |
Table 54. Nested Elements for match
Name | Description | Required |
---|---|---|
arg | Specifies the name and value of the parameters that are needed by the Matcher class, in addition to the actual column values, to compute the match. | Zero or more arg elements may need to be specified |
Specifying a perccentage matcher with 20% tolerance
<match col-id="1-2" matcher="net.sourceforge.sqlunitmatchers.PercentageRangeMatcher"> <arg name="pc-tolerance" value="20" /> </match> |
The field tag is used to describe a field of a user-defined data type (UDT) object returned as a STRUCT type. The returned object is treated as a JavaBean, and the fields are the bean properties. Nested UDT objects can be specified using a struct tag as the body of the field. Fields with null values have NULL as their body.
field ::= (BODY)|(struct) |
Table 56. Nested Elements for field
Name | Description | Required |
---|---|---|
struct | A field whose type is another UDT instead of a 'simple' type is specified by a nested struct tag. Like top-level UDTs, the type and class must be specified in a typedef tag. | Zero or one |
Returning nested UDTs as STRUCTs.
<struct> <field name="capacity">30</field> <field name="handler"> <struct> <field name="name">AEF Gripper</field> <field name="workLoad">12.5</field> </struct> </field> <field name="storage">NULL</field> </struct> |
The sub tag calls a partially defined stored procedure or SQL call in a preceding subdef tag.
sub ::= |
Table 58. Nested Elements for sub
Name | Description | Required |
---|---|---|
subparam | Specifies a value for the parameter for the stored procedure or SQL call that was declared in the subdef tag. Lookup is by parameter name. | Zero or more |
Calling a sub with parameters
<sub lookup="UpsertStreet"> <subparam name="street" value="Market Street" /> </sub> |
Specifies an expected exception with expected error code and message
exception ::= (code)?, (message)? |
None
An exception declaration
<exception> <code>0</code> <message>ERROR: Cannot insert a duplicate key into unique index ux2_employee</message> </exception> |
The diff element is used to compare the results of two SQL queries or stored procedure calls. This scenario can be used to the results of a database load or when the results are either too long or unknown at the time the test specification is being written. The two queries/calls can either use the same Connection or use their own dedicated Connection to the same or different databases. The result tag is not specified in case of diff. SQLUnit will internally generate the two Result objects and match them. The default matching is exact equality, but can be overriden by supplying one or more match elements in the diff element. More information on Matching can be found in the User-Defined Matching section
diff ::= ((skip)?, (classifiers)?, (match)*, (prepare)?, (sql|call), (sql|call)) |
Table 60. Attributes for diff
Name | Description | Required |
---|---|---|
name | The name of the test used by SQLUnit to report progress messages in its log output. | Yes |
assert | Specifies a single assertion or a comma-separated list of assertions which must be true for this diff. | No, defaults to equal if not specified |
failure-message | If specified, SQLUnit will print the user-supplied failure message if the test failed. | No |
java-object-support | If specified, Java Object Support is enabled for the test | No, default is false |
multi-threaded | If set to true, runs the calls in parallel to save time | No, default is false (serial execution) |
Table 61. Nested Elements for diff
Name | Description | Required |
---|---|---|
skip | Indicates whether the diff should be skipped or not. | No |
classifiers | Allows user to provide classification criteria for the diff which SQLUnit can use to decide whether it should run the diff or not based on criteria provided to match the classifier. | No |
match | Provides overrides for the matching strategy on a per column basis | No |
prepare | Allows per test setup calls | No. Zero or one prepares can be specified. |
sql | Specifies the SQL statement to execute. | Either one of sql or call needs to be specified. Two and only two needs to be specified |
call | Specifies the stored procedure to execute. | Either one of sql or call needs to be specified. Two and only two needs to be specified. |
Diff call with multiple match elements
<diff name="Diffing different resultset/multiple matchers" failure-message="Diff test #3 failed"> <match col-id="1" matcher="net.sourceforge.sqlunitmatchers.AllOrNothingMatcher"> <arg name="match" value="true" /> </match> <match col-id="2" matcher="net.sourceforge.sqlunitmatchers.RangeMatcher"> <arg name="tolerance" value="50" /> </match> <match col-id="3" matcher="net.sourceforge.sqlunitmatchers.PercentageRangeMatcher"> <arg name="pc-tolerance" value="10" /> </match> <sql connection-id="1"> <stmt>select widget_name, price_per_unit, number_sold from widgets where widget_id=?</stmt> <param id="1" type="INTEGER">1</param> </sql> <sql connection-id="2"> <stmt>select widget_name, price_per_unit, number_sold from widgets where widget_id=?</stmt> <param id="1" type="INTEGER">2</param> </sql> </diff> |
Allows caller to group a test by category
category ::= (BODY) |
None
None
Carries argument values and types for the containing element
arg ::= (EMPTY) |
None
Specifying args for jndi
<arg name="java.naming.factory.initial" value="org.jnp.interfaces.NamingFactory" /> |
Specifying args for methodArgs
<methodArgs> <arg name="col1" type="java.lang.String" value="ABC" /> </methodArgs> |
The sql tag describes a regular SQL statement (not a stored procedure) with or without replaceable parameters. It can be used to describe a stored function call for databases that support it. It is converted internally to a JDBC PreparedStatement object. SQL specified by the sql statement can return a result with a single resultset or an updatecount.
sql ::= (stmt, (param)*) |
Table 63. Attributes for sql
Name | Description | Required |
---|---|---|
id | The name or number of the sql call | No |
connection-id | When multiple Connections are defined in a SQLUnit test, this attribute refers to the Connection to use for running this call. If not specified, SQLUnit tries to look up the default Connection. | No |
Table 64. Nested Elements for sql
Name | Description | Required |
---|---|---|
stmt | Specifies the actual SQL statement, with or without replaceable parameters in the body of the tag. | Yes |
param | Occurs once for each replaceable parameter, if specified, for the SQL string. | Yes, if there are replaceable parameters in the SQL string. |
Example of a simple sql tag
<sql> <stmt>select custId from customer where custId=?</stmt> <param id="1" type="INTEGER">1</param> </sql> |
The dynamicsql tag invokes a named method in a named class in order to generate a SQL string dynamically, which is then fed to SQLUnit for testing against a known result. This was included because it is often necessary to test dynamic SQL that is built in response to known conditions, and the results are known, but the actual SQL may not be of interest.
dynamicsql ::= ((constructorArgs)*, (methodArgs)*) |
Table 65. Attributes for dynamicsql
Name | Description | Required |
---|---|---|
static | If set to true, specifies that the method is a static method | No, default is false (non-static method) |
class | Specifies the full class name where the method is defined | Yes |
method | Specifies the method name to invoke | Yes |
id | The name or number of the sql call | No |
connection-id | When multiple Connections are defined in a SQLUnit test, this attribute refers to the Connection to use for running this call. If not specified, SQLUnit tries to look up the default Connection. | No |
Table 66. Nested Elements for dynamicsql
Name | Description | Required |
---|---|---|
constructorArgs | Wraps a set of arg elements which specify the arguments the constructor for the class will take | Not required if this is a static method, or if the class has a default null constructor |
methodArgs | Wraps a set of arg elements which specify the arguments to pass to the method | Not required if the method does not take arguments |
A dynamicsql tag that invokes a static method
<dynamicsql class="net.sourceforge.sqlunit.utils.TestArgument" static="true" method="getGeneratedOracleSqlString"> </dynamicsql> |
<<< Previous | Home | Next >>> |
SQLUnit Canoo2HTML Tool | Extending SQLUnit: Writing your own tag handler |