开发者

DB Unit Testing framework?

开发者 https://www.devze.com 2023-03-25 00:58 出处:网络
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.

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 suggest开发者_如何学JAVAion is appreciated. Thanks.


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.


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.

From my other answer posted earlier in the day, yes, this is possible using DbUnit. (Based on your edit, you don't need this; the subsequent section of my answer addresses why I use DbUnit, and when I wouldn't use it).

The following code snippet demonstrates how the setup of every test is performed:

@Before
public void setUp() throws Exception
{
    logger.info("Performing the setup of test {}", testName.getMethodName());
    IDatabaseConnection connection = null;
    try
    {
        connection = getConnection();
        IDataSet dataSet = getDataSet();
        //The following line cleans up all DbUnit recognized tables and inserts and test data before every test.
        DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);
    }
    finally
    {
        // Closes the connection as the persistence layer gets it's connection from elsewhere
        connection.close();
    }
}

private IDatabaseConnection getConnection() throws Exception
{
    @SuppressWarnings({ "rawtypes", "unused" })
    Class driverClass = Class.forName("org.apache.derby.jdbc.ClientDriver");
    Connection jdbcConnection = DriverManager.getConnection(jdbcURL, "XXX",
            "YYY");
    IDatabaseConnection databaseConnection = new DatabaseConnection(jdbcConnection);
    return databaseConnection;
}

private IDataSet getDataSet() throws Exception
{
    ClassLoader classLoader = this.getClass().getClassLoader();
    return new FlatXmlDataSetBuilder().build(classLoader.getResourceAsStream("database-test-setup.xml"));
}

The database-test-setup.xml file contains the data that will be inserted into the database for every test. The use of DatabaseOperation.CLEAN_INSERT in the setup method ensures that all the tables specified in the file will be cleared (by a delete of all rows) followed by an insert of the specified data in the test data file.

Avoiding DbUnit

I use the above approach specifically to clear out sequences before the start of every test, as the application uses a JPA provider which updates the sequences in a separate transaction. If your application is not doing anything like that, then you can afford to simply start a transaction in your setup() method and issue a rollback on teardown after the test. If my application didn't use sequences (and if I didn't desire to reset them), then my setup routine would have been as simple as:

@Before
public void setUp() throws Exception
{
    logger.info("Performing the setup of test {}", testName.getMethodName());
    // emf is created in the @BeforeClass annotated method
    em = emf.createEntityManager();
    // Starts the transaction before every test
    em.getTransaction.begin();
}

@After
public void tearDown() throws Exception
{
    logger.info("Performing the teardown of test {}", testName.getMethodName());
    if (em != null)
    {
        // Rolls back the transaction after every test
        em.getTransaction().rollback();
        em.close();
    }
}

Also, I use dbdeploy with Maven, but that is primarily for keeping the test database up to date with the versioned data model.


Spring's test framework does exactly that for you.


I'd handled it following ways.

When the project is in test mode. I'd used bootstraping data to to test using dbdeploy Fixed data that you can assert on. and use the dao directly to test the DAO and DB layer of your application.

Hope it helps

Update

for example there is an entity called Person in your system, now what you can test on this is basic CRUD operations.

  • Run bootstraping data scripts to laod the data
  • retrieve all the persons from DB and assert on it. like wise see all the CRUD

to rollback the transaction you can mark

@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)

so it will rollback the DB stuff

0

精彩评论

暂无评论...
验证码 换一张
取 消