-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Description
In practice, you have to test several DB users and miscelaneous tables using one connection. Due to e.g. performance reasons you would not reopen a new connection and close the old one.
In worst cases you want to keep the DB connection, and not to lose data with in-memory DB.
In most cases the programmer would share static context among tests through test suite.
Actually dangerous solution!
Here i come with an update to
org.junit.runners.JUnit4
and org.junit.runners.Suite
, where the suite tries to inject suite instance (fail-safe) in to public field on an instance of test annotated by @parent (must be added to framework).
All loks like this:
@RunWith(Suite.class)
@SuiteClasses({MyTest.class})
public final class TestSuite implements IParentDB {
private final DBConnection connection;
public TestSuite() {
connection = new DBConnection();
}
@Override
public IDBConnection getConnection() {
return connection;
}
@Suite.SuiteFinished
public void done() {
if (connection != null) connection.close();
}
}
@RunWith(org.my.JUnit4.class)
public final class MyTest {
@Parent
public IParentDB parent;
@Test
public void testDB() {
assertNotNull(parent);
assertNotNull(parent.getConnection());
}
}
, where IParentDB is a custom type.
Thus all the tests similar to MyTest now are able to share DB connection without any need to maintain the test suite vice-versa.
As an advantage, the method done() in the suite is called when all tests finished.
I tested in my scenario with two tests and the single instance of the suite in all the life cycle of both tests.
When integrated to JUNit 4, we would not need to specify a custom @RunWith(org.my.JUnit4.class).