[英]Clean up database after JUnit test.
I have a unit test that inserts rows into the database, and I'd like DBUnit to automatically clean up those rows afterwards (DBUnit does not initially insert those rows - that's purely the responsibility of the code being tested). 我有一个将行插入数据库的单元测试,并且我希望DBUnit之后自动清除这些行(DBUnit最初不插入那些行-纯粹是被测试的代码的职责)。
Thanks. 谢谢。
使您的INSERT / UPDATE / DELETE查询具有事务性,并在测试完成后回滚它们。
If you use JUnit4, then you can declare a function with @AfterClass
annotation: it will execute after all tests and you can remove all the rows you added in your tables. 如果使用JUnit4,则可以声明带有
@AfterClass
批注的函数:它将在所有测试之后执行,并且可以删除在表中添加的所有行。
In JUnit3, you don't have any equivalent, but you can override the tearDown()
method, which will be executed after each test (equivalent of @After
annotation in JUnit4). 在JUnit3中,您没有任何等效项,但是您可以重写
tearDown()
方法,该方法将在每次测试后执行(等效于JUnit4中的@After
注释)。
If you allocate external resources(file/DB) in a Before method you need to release them after the test runs. 如果您使用Before方法分配外部资源(文件/数据库),则需要在测试运行后释放它们。 Annotating a public void method with @After causes that method to be run after the Test method.
用@After注释公共无效方法会导致该方法在Test方法之后运行。 All @After methods are guaranteed to run even if a Before or Test method throws an exception.
即使@Before或Test方法引发异常,也保证所有@After方法都可以运行。 The @After methods declared in superclasses will be run after those of the current class.
在超类中声明的@After方法将在当前类的方法之后运行。
Example shows file as resource but you can use it for your DB cleanup. 示例将文件显示为资源,但您可以将其用于数据库清理。
public class Example {
File output;
@Before public void createOutputFile() {
output= new File(...);
}
@Test public void something() {
...
}
@After public void deleteOutputFile() {
output.delete();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.