Sharing setUp() and tearDown() code for all tests - I
by, 05-21-2011 at 11:29 PM (1213 Views)
You may wish to share the code written in setUp() and tearDown() methods of your JUnit tests. This clearly will indicate that you have excessive coupling in your design. Coupling is not bad always but if more tests share the same test fixture state, then this indicates that the classes under test have some undesirable dependencies.
You may wish to remove these dependencies but its another stories. As I said, coupling or dependencies are not always bad. But if you wish to keep coupling minimum, then tery refactoring the design to further decouple the classes under test and eliminate code duplication is usually a better investment than setting up a shared test fixture.
But if you really wish to decouple the design, then decouple the classes under test and try to eliminate code duplication.
@BeforeClass and @AfterClass annotations are used to define the execution plan for methods. Add a @BeforeClass annotation to a method to be run before all the tests in a class, and a @AfterClass annotation to a method to be run after all the tests in a class.