Published March 23, 2020
by Doug Klugh
Avoiding Slow Tests
Define the state of your test environment by designing and building a Persistent Test Fixture to share system resources across a suite of tests. This will help optimize test execution by managing resources that are expensive to allocate (such as database connections) that can be setup once and shared across multiple tests. Be sure not to persist resources with side effects as this will create coupling between tests and inhibit independent and concurrent testing.
We can inhibit slow running tests by re-using the same instance of a test fixture across multiple tests. Not having to destroy and recreate the fixture for each test will, in many cases, greatly reduce the execution time. If there are any objects that the tests need to modify or delete, then those objects should be built by each test as a Fresh Fixture.
The downside is that a fixture that is designed to be shared across multiple tests is likely to be much more complex than a Fresh Fixture — leading to a Fragile Fixture. It also leads to Obscure Tests since the fixture is constructed outside of the tests.
A Persistent Fixture is one that allows some state (or resource) to persist from test to test. Sharing resources across a suite of tests can be accomplished in JUnit using the @BeforeClass attribute to designate suite setups and the @AfterClass attribute to designate suite teardowns.