1

I am trying to use dbunit to test the database of the system. Since several testcases can be tested using same dataset, I want to init the dataset once for all of them. But I also use @AutoWire of spring to init those db connection parameter.

I tried to use @BeforeClass and @AfterClass to setup the db. But turns out the @Autowire happens when class get initiated(not seems not work for auto wire static members).

So wondering is there any other way i can setup/tear down the db dataset before/after all the testcases?

I found one elegant solution:

How to allow instance methods to run as JUnit BeforeClass behavior

This post basically explained a way to change unittest runner to trigger the events. And for spring, the AbstractTestExecutionListener can be used as well

Enzhou Liu
  • 21
  • 4

2 Answers2

0

Just initialize database using the ApplicationListener interface. Please take a look at this question: How to add a hook to the application context initialization event? It is possible to create all the data in the onApplicationEvent method.

Anyway don't use dbunit, just create all your tests with @Transactional, and @DirtiesContext (DirtiesContext on the class level) using ClassMode=AfterEachTestMethod So the code would be like this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:testContext.xml" })
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
public class YourTestClassTest {
    //...
}
Community
  • 1
  • 1
BlueLettuce16
  • 2,013
  • 4
  • 20
  • 31
  • I found a solution posted above. thanks for your help. But i am looking two instance level beforeclass and afterclass. – Enzhou Liu Nov 12 '14 at 21:08
0

I also use DBUnit for my integration tests and i setup/teardown the data within the @Before and @After annotated methods instead of @BeforeClass/@AfterClass. so each test gets its refreshed test-data.

To use different datasets for each tests or different replacements for a single test you also could call a setup(dataSet) or setup(replacementList) method as first row of your @Test annotated method (than you don't us @Before annotation).

Niels
  • 302
  • 1
  • 2
  • 9