Adding a setUp step for multiple JUnit test classes
Asked Answered
M

3

6

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 ?

Menon answered 27/8, 2013 at 8:32 Comment(0)
C
4

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.

Chervonets answered 27/8, 2013 at 9:1 Comment(1)
@BeforeClass sounds like a solution. But I was using a static initializer in my SuperTestClass to achieve this and was checking whether there are any non-static solution. 'BeforeClass' basically does the same if I'm not wrong.Menon
Y
0

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.

Yawning answered 27/8, 2013 at 8:35 Comment(1)
I'm not sure whether this answers the last part of my question. A super class method with @Before annotation will run multiple times if my test suite has multiple test classes.Menon
M
0

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

Messily answered 27/8, 2013 at 21:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.