Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit before class ( non static )

Tags:

java

junit

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.

like image 631
Roman Avatar asked May 13 '10 09:05

Roman


People also ask

Does BeforeClass have to be static?

JUnit's @BeforeClass annotation must be declared static if you want it to run once before all the @Test methods. However, this cannot be used with dependency injection.

What is the difference between @before and @BeforeClass annotation?

The code marked @Before is executed before each test, while @BeforeClass runs once before the entire test fixture.

What will happen when a JUnit return type is changed from void to any other type?

All the JUnit test methods should have a void return type. otherwise it will be ignored. If the return type of a test method is changed, it would not be considered as a test method and would be ignored during execution of tests.


2 Answers

A simple if statement seems to work pretty well too:

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:test-context.xml"}) public class myTest {      public static boolean dbInit = false;      @Autowired     DbUtils dbUtils;      @Before     public void setUp(){          if(!dbInit){              dbUtils.dropTables();             dbUtils.createTables();             dbInit = true;          }     }   ... 
like image 124
Upgradingdave Avatar answered Sep 23 '22 10:09

Upgradingdave


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 */ } 

NOTE: DO NOT overlook/miss DependencyInjectionTestExecutionListener while adding custom TestExecutionListeners. If you do, all the autowires will be null.

like image 33
Espen Avatar answered Sep 25 '22 10:09

Espen