Passing in a Connection object to SQLUnit

You can also embed SQLUnit inside your application, in which case you do not need to specify the connection element in the XML file at all. The only downside to this approach is that you are restricted to only a single database connection. To do this, build the Connection object in your application, and set the Connection object for the SQLUnit object. A code snippet to do this would look something like this:


    // Instantiate SQLUnit
    SQLUnit sqlunit = new SQLUnit("sqlunit");
    // set the properties
    sqlunit.setTestFile("/my/test/file.xml");
    sqlunit.setHaltOnFailure(false);
    sqlunit.setDebug(false);
    sqlunit.setReporter(new TextReporter("/my/report/file.xml"));
    // set the Connection
    sqlunit.setConnection(conn);
    // run the tests
    try {
        sqlunit.runTest();
    } catch (SQLUnitException e) {
        // report the exception
    }
      

Note that you can also choose to supply the Connection information inside the XML files themselves using any of the methods described above, and not specify the setConnection() method at all. SQLUnit will then read the Connection properties from the XML files and run the tests using these Connections.