1

After I run a bunch of Selenium (jUnit4) tests using Maven, I'd like to do a database clean-up (remove things they inserted etc). It's an older project running on Tapestry/Spring/Hibernate and a legacy database. I'd like to do the clean up in an @After annotated method - but injecting of DAO's/Managers/SessionFactory doesn't work.

The testing goes like this: I run (mvn jetty:run-war) the app in one console, and start the testing in another console (mvn test) - it accesses the app on localhost:8080.

John Manak
  • 13,328
  • 29
  • 78
  • 119
  • You can take a look at this question: http://stackoverflow.com/questions/82949/before-and-after-suite-execution-hook-in-junit-4-x – sblundy Jan 13 '11 at 14:09
  • You you looking for a hint how to fix your problem: "but injecting of DAO's/Managers/SessionFactory doesn't work." or for an other way to setup and reset your test data? – Ralph Jan 13 '11 at 17:54

2 Answers2

6

Several possible approaches:

  1. Use dbunit, which is designed to return a database to a know state between tests.
  2. Wrap each test in a database transaction with a try{} finally{} block where the finally rolls back the transaction.
  3. Use a database strictly for testing and don't worry about it. Make your tests create uniquely identified / named values each time so you don't have conflicts, but otherwise don't take any action.
orangepips
  • 9,891
  • 6
  • 33
  • 57
  • 2
    +1 I use strategy 3 (and sometimes strategy 2) but get into a lot of arguments about it. You can't always guarantee returning the system to its original state (for example if you have a business method which commits a transaction and you need to test that, if your program crashes after the commit but before your cleanup code then you've got junk in your DB). Given you might sometimes have junk in your DB you've got to use a test database and then you might as well just relax and save the time writing any cleanup code at all. – Adrian Smith Jan 13 '11 at 14:16
  • 1
    @Adrian Smith: agreed. Another way of thinking about it is the more people (programmers, testers, etc...) involved, the more likely you are to end up at #3 because doing anything becomes unworkable. – orangepips Jan 13 '11 at 14:22
0

I would rather use

@Transactional

anotation above method declaration. It runs rollback after each test. It works fine for me.

For example:

@Test
@Transactional  
public void simpleTest(){    
    // your logic here     
}
Heril Muratovic
  • 1,940
  • 6
  • 25
  • 46