In a project there are multiple test classes each containing multiple test methods. Say, I want to create a database connection before running each of these test classes. The connection should be made regardless of whether I run an individual test class, multiple test classes or a test suite. Most importantly this step should not be called over and over again in case of multiple test classes. The connection should be made only once regardless of number of test classes I'm running.
Could you suggest a design or any JUnit tips to tackle this issue ?
Discussion. As outlined in Recipe 4.6, JUnit calls setUp( ) before each test, and tearDown( ) after each test. In some cases you might want to call a special setup method once before a series of tests, and then call a teardown method once after all tests are complete.
The @BeforeClass methods of superclasses will be run before those the current class. The difference being that setUpBeforeClass is run before any of the tests and is run once; setUp is run once before each test (and is usually used to reset the testing state to a known-good value between tests).
You could run the classes in a test suite. Refer this question and the answers provided.
Or change your design and use @BeforeClass
annotation to run setup once before each test class.
Sometimes several tests need to share computationally expensive setup (like logging into a database). While this can compromise the independence of tests, sometimes it is a necessary optimization. Annotating a public static void no-arg method with @BeforeClass causes it to be run once before any of the test methods in the class. The @BeforeClass methods of superclasses will be run before those the current class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With