Before JUnit runs each test... method, it calls setup (). After each test method is complete, it calls teardown (). Therefore, you can set and clean up the test environment and release resources in these two methods, such as opening and closing the database connection.
Public class testdb extends testcase ...{
Private connection dbconn;
Protected void setup ()...{
Dbconn = new connection ("oracle", 1521, "XXX", "XXX ");
Dbconn. Connect ();
}
Protected void teardown ()...{
Dbconn. Disconnect ();
Dbconn = NULL;
}
Public void testxxx ()...{
...
}
Public void testyyy ()...{
...
}
}
Similarly, setting up the environment for the entire test suite and releasing resources can also be placed in per-Suite setup and per-Suite tear-down. To implement per-Suite setup and per-Suite tear-down, you need to package the suite to be tested into a testsetup object.
Import JUnit. Framework .*;
Import JUnit. Extensions .*;
Public class testclasstwo extends testcase ...{
Public testclasstwo (string method )...{
Super (method );
}
Public void testxxx ()...{
...
}
Public void testyyy ()...{
...
}
Public Static Test Suite ()...{
Testsuite suite = new testsuite ();
Suite. addtest (New testclasstwo ("testxxx "));
Testsetup wrapper = new testsetup (suite )...{
Protected void setup ()...{
Onetimesetup ();
}
Protected void teardown ()...{
Onetimeteardown ();
}
};
Return wrapper;
}
Public static void onetimesetup ()...{
Dbconn = new connection ("oracle", 1521, "XXX", "XXX ");
Dbconn. Connect ();
}
Public static void onetimeteardown ()...{
Dbconn. Disconnect ();
Dbconn = NULL;
}
}