Is there any write up of the correct way to write new Junit tests?
I am trying to follow the junit cookbook when writing new junit tests.
http://junit.sourceforge.net/doc/cookbook/cookbook.htm
I do have some thoughts on how to write new JUnit Tests.
When writing tests for Derby (using JDBC), I think most tests need to
have access to some configuration data, like jdbc url, jdbc classname
etc. This could be put/gathered into a immutable singleton object
(i.e DerbyTestConfig) which can be accessed by the tests.
Alternatively it could be gathered in a common testcase class, like
DerbyJUnitTestCase, however then you may need to duplicate this code if
you make i.e TestDecorators which are not subclasses of DerbyJUnitTestCase.
Since many tests are using JDBC connections, it could be useful to have
a common TestCase base class which sets up a connection in the setUp()
and closes it in the tearDown(). I.e:
class DerbyConnectionTestCase extends TestCase {
protected Connection con;
final void setUp() throws Exception
{
con = DriverManager.connect(config.getJdbcUrl(), ..);
doSetup();
}
final void tearDown() throws Exception
{
doTearDown();
con.close(); <- of course with some better exception handling..
}
..
}
I think a big mistake we made with the old harness was no formal way to
add Java tests, which meant multiple ways to start the engine and obtain
the connection and multiple utility methods (almost) performing the same
action.
When it comes to setting up additional fixture before running a set of
testcases, I think a powerful and reusable mechanism is the
junit.extensions.TestSetup. I.e one could make a DerbyNetworkServerSetup
class. In its setUp() method it starts the network server, and in the
tearDown() in stops it. So if you have a suite of tests which requires
a running network server, they can be wrapped like this:
TestSuite suite = new TestSuite(MyDerbyTestCase.class);
Test t = new DerbyNetworkServerSetup(suite);
When running Test t, it will first call setUp() in
DerbyNetworkServerSetup, then it will run all testcases in
MyDerbyTestCase, and finally call tearDown() in DerbyNetworkServerSetup.
Of course, one should consider if DerbyNetworkServerSetup should simply
do nothing if the test is only testing in embedded mode (i.e make it
dependent on the test configuration).
Would be nice if there were guidelines provided by whoever set up the
initial Junit framework.
I think Rick H /David set it up, so maybe they have some more guidelines
or ideas.
--Andreas