Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DB Unit Testing framework?

In my project, I've used spring, jpa with PostgreSQL DB, I've lots of table in DB and I need to have Unit testing of all of them.

Is there any framework which just rollback all the transactions after each test finished so every test will have fresh/same DB data to Test. And this way after all Test executions, data of DB schema would be as it is.

Any suggestion for this?

I've some idea of DBUnit but in that I need to write .xml files for every input data for every test and need to insert data in setup() and clear/remove data in tearDown(), but doesn't seems better strategy to me.

Any suggestion is appreciated. Thanks.

like image 549
SmartSolution Avatar asked Aug 04 '11 12:08

SmartSolution


1 Answers

As @Ryan indicates .... the Testing section of the Spring Reference manual should be consulted.

Some startup tips...

We've handled this using Spring's AbstractTransactionalJUnit4SpringContextTests.

For example, we define an abstract superclass:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:WebContent/WEB-INF/testconfig/test-web-application-config.xml")
@TransactionConfiguration()
@Transactional
public abstract class OurAbstractTransactionalSpringContextTest extends AbstractTransactionalJUnit4SpringContextTests {
}

And then individual subclasses which need additional context get defined as:

@ContextConfiguration("classpath:path/to/config/ConfigForTestCase.xml")
public class TestOurFunction extends OurAbstractTransactionalSpringContextTest {
    @Test
    public void testOurMethod() {
    }

}

Note that:

  1. Not all test classes need additional context for them, skip the @ContextConfiguration on the particular subclass.
  2. We execute via ant and use the forkmode="perBatch" attribute on the junit task. That ensures all tests run with the same context configuration (saves from reloading the Spring context for each test). You can use the @DirtiesContext to indicate that the context should be refreshed after a method/class.
  3. mark each method with the @Test annotation. The Spring framework doesn't pick up methods using Junit's public void testXXX() convention.
like image 77
Jacob Zwiers Avatar answered Sep 28 '22 05:09

Jacob Zwiers