views:

22

answers:

2

I am using the @BeforeClass annotation to ensure that a set of activities are done just once in a set of 5-6 tests. There is a hierarch of 3 java files.

File1 extends TestCase

File2 extends File 1 (this is where i have to put the beforeclass annotation at the setUp method)

File3 extends File2 (File 3 has the tests.. 5 in number, but i want the setup in file 2 to be run just once)

Right now, the setUp method in File 2 is being called before every test in File3. even after putting the @BeforeClass annotation. What can i do to ensure that this setup runs only once for all the tests in File 3

+2  A: 

Since you are extending TestCase class, so setUp method is getting called before start of every test. For junit 4 onwards, you don't need to extend TestCase class. Just try to remove it and it should work. You will also need to add @Test annotation on test method

Ankit
@ankit, thanks for the reply. But what will happen to the setUp and tearDown methods then? the ones which were supposed to run everytime a test is run. I guess the @beforeclass annotation wont do for the regular setUp methods. Whcih annotation should i use here, if any?
encryptor
You can use @Before and @After annotations for setUp and tearDown respectively.
Ankit
Now is it necessary to make the @beforeclass method static? If that is required, then everything inside will have to be made static too. is there a way to avoid making the mwthod static and stil going ahead with @beforeclass ?
encryptor
as far as I remember, there is no way to avoid making @beforeclass method static.
Ankit
+2  A: 

I suspect that you're using a JUnit 3 TestRunner, which ignores annotations and uses only naming conventions (where setUp() is conventionally run before every test). Try having a method with the @Test annotation but not starting with "test" - if it's not run, you're using the JUnit 3 TestRunner.

So, to fix this, use the JUnit 4 TestRunner to start the test suite.

Michael Borgwardt