tags:

views:

425

answers:

4

Are there any best practices to get Junit execute a function once in a test file , and it should also not be static.

like @BeforeClass on non static function?

Here is an ugly solution :

@Before void init(){
    if (init.get() == false){
        init.set(true);
        // do once block
    }
}

well this is something i dont want to do , and i am looking for an integrated junit solution.

A: 

I've never tried but maybe you can create a no-argument constructor and call you function from there?

Roman
This would work , the problem is that I need the possibility to override this action in the classes that extend this base test class
Roman
@Roman: oh, now I see. Add this to your post, this comment makes things much clearer.
Roman
+2  A: 

To use an empty constructor is the easiest solution. You can still override the constructor in the extended class.

But it's not optimal with all the inheritance. That's why JUnit 4 uses annotations instead.

Another option is to create a helper method in a factory/util class and let that method do the work.

If you're using Spring, you should consider using the @TestExecutionListeners annotation. Something like this test:

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({CustomTestExecutionListener.class, 
     DependencyInjectionTestExecutionListener.class})
@ContextConfiguration("test-config.xml")
public class DemoTest {

Spring's AbstractTestExecutionListener contains for example this empty method that you can override:

public void beforeTestClass(TestContext testContext) throws Exception {
    /* no-op */
}
Espen
A: 

How about making an abstract test class that has a default setUp method

public abstract class ParentTest { 

    @Before
    public void setUp() {
        // generic initialization
    }
}

and then override or extend it in the other tests?

public class ChildTest extends ParentTest {

    @Before
    public void setUp() {
        super.setUp();
        // add specific initialization
    }
}
matsev
The setUp method is called , every test , this is exactly what I not wanted...
Roman
+1  A: 

If you don't want to set up static initializers for one time initialization and are not particular about using JUnit, take a look at TestNG. TestNG supports non static one time initialization with a variety of configuration options, all using annotations. In TestNG, this would be equivalent to:

@org.testng.annotations.BeforeClass
public void setUpOnce() {
   // One time initialization.
}

For teardown,

@org.testng.annotations.AfterClass
public void tearDownOnce() {
   // One time tear down.
}

For JUnit 4 equivalent of @Before and @After, you can use @BeforeMethod and @AfterMethod respectively.

Thanks,

Kartik

Kartik