tags:

views:

290

answers:

5

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.

+2  A: 

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

krosenvold
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.
furtelwart
yes, you're right
krosenvold
+2  A: 

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

Volker

ShiDoiSi
A: 

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.

Bhushan
A: 

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.

Aaron Digulla
+1  A: 

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

public class CountTest {
  static int count;

  @BeforeClass
  public static void beforeClass() {
    count = 0;
  }

  @Before
  public void countUp() {
    count++;
  }

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

  @Test
  public void test1() {
    assertTrue(true);
  }
  // some more tests

Output will be, e.g.:

5 tests.

furtelwart