Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a setUp step for multiple JUnit test classes

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 ?

like image 307
rclakmal Avatar asked Aug 27 '13 08:08

rclakmal


People also ask

Is JUnit setUp called for each test?

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.

Does setUp run before every test?

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).


1 Answers

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.

like image 65
Nufail Avatar answered Sep 20 '22 01:09

Nufail