Take the 2-minute tour ×

Is there a way to know the number of test methods in a test case?

What I want to do is have a test case which tests several scenarios and for all these i would be doing the data setUp() only once. Similarly I would like to do the cleanup (tearDown()) once at the end of all the test methods.

The current approach i am using is to maintain a counter for the number of test methods that are present in the file and decrement them in the tearDown method and do the cleanup when the count reaches 0. But this counter needs to be taken care of whenever new test methods are added.

share|improve this question
Regarding finding the number of test methods in a junit TestCase -- you can do this via reflection. –  Marco Sep 30 '11 at 10:16
add comment

5 Answers

up vote 4 down vote accepted

Instead of using setup/teardown you should probably use methods annotated with @BeforeClass and @AfterClass instead.

share|improve this answer
As he did not provide neither his Java nor his JUnit version, I would like you to add the information, that it won't work with java < 5 or junit < 4.x. –  guerda Feb 12 '09 at 12:26
yes, you're right –  krosenvold Feb 12 '09 at 12:58
add comment

You can do this through @BeforeClass and @AfterClass in JUnit4: http://junit.org/apidocs/org/junit/BeforeClass.html


share|improve this answer
add comment

If you are using Junit4 and the suggestion given by others is the correct one. But if you using earlier version then use this technique to achieve what you want -

You can define a suite for all those tests for which you want to setup and teardown only once. Take a look at junit.extensions.TestSetup class. Instead of executing your test classes you need to then execute these suites.

share|improve this answer
add comment

A solution for junit 3 is to call a special setup method in every test which checks a static flag. if the flag is not set, run the global setup. If it is, skip the setup.

Make sure the global setup is properly synchronized if you want to run tests in parallel.

share|improve this answer
add comment

Short example for counting tests with @BeforeClass, @AfterClass and @Before.

public class CountTest {
  static int count;

  public static void beforeClass() {
    count = 0;

  public void countUp() {

  public static void printCount() {
    System.out.println(count + " tests.");

  public void test1() {
  // some more tests

Output will be, e.g.:

5 tests.

share|improve this answer
add comment

Your Answer


