mysql表还原初始状态,如何使用dbUnit将数据库恢复到初始状态?

I am new to automated testing and dbUnit. So I would appreciate your advice.

I am going to create a test suite, that will run the following way:

create an in-memory H2 database

run DDL scripts to create tables

run dbUnit to insert initial data (let's call it STATE0) that will be used by all tests.

run tests

Till there it looks nice for me, but what I don't understand, is how do I revert the database to the STATE0 after a test run and changed the data?

Can I do it with dbUnit?

Or with something else?

Should I recreate the database before each test?

Simple not commiting transactions in tests is not appropriate for me, because the tests will eventually run more than one transaction over may be more than one database connection.

解决方案

DBUnit can do the work four you automatically if you write your @BeforeClass, @Before and @After methods properly. E.g. in our project, using Derby, one such test case looks like

public class MyTest {

protected static IDataSet getDataSet() throws Exception {

URL url = MyTest.class.getClassLoader().getResource("MyDataSet.xml");

return new XmlDataSet(new FileInputStream(url.getPath()));

}

private static JdbcDatabaseTester databaseTester;

@BeforeClass

public static void setUpClass() throws Exception {

// Init test environment, session etc.

databaseTester = new JdbcDatabaseTester(

"org.apache.derby.jdbc.ClientDriver",

"jdbc:derby://localhost:1527/myschema",

"username", "password");

databaseTester.setDataSet(getDataSet());

}

@AfterClass

public static void tearDownClass() {

// Close session etc.

}

@Before

public void setUp() throws Exception {

databaseTester.onSetup();

}

@After

public void tearDown() throws Exception {

databaseTester.onTearDown();

}

@Test

public void test() throws Exception { ... }

}

This code puts back (a subset of) the DB schema to the state defined by MyDataSet.xml after each test. (Note that, as @Pascal commented, the reset may not always be full - if a test modifies a table which is not in the dataset, it won't be affected by the @Before / @After methods.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值