Reputation: 1982
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 ?
Upvotes: 6
Views: 3411
Reputation: 4895
If you're using spring-test, then you could use the technique employed here: How to load DBUnit test data once per case with Spring Test
Upvotes: 0
Reputation: 1598
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.
Upvotes: 4
Reputation: 68715
Use @Before Junit annotation
When writing tests, it is common to find that several tests need similar objects created before they can run. Annotating a public void method with @Before causes that method to be run before the Test method. The @Before methods of superclasses will be run before those of the current class.
Simply introduce a superclass for all your junit classes. You can put the database connection logic in your Superclass @Before annotated method.
Upvotes: 0