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.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…