我派生自这个基类,以便将每个单独的测试封装到一个回滚的事务中
public abstract class TransactionBackedTest { private TransactionScope _transactionScope; [SetUp] public void TransactionSetUp() { var transactionOptions = new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted,Timeout = TransactionManager.MaximumTimeout }; _transactionScope = new TransactionScope(TransactionScopeOption.required,transactionOptions); } [TearDown] public void TransactionTearDown() { _transactionScope.Dispose(); } }
使用这个我也尝试以相同的方式设置TestFixure事务:
[TestFixture] class Example: TransactionBackedTest { private TransactionScope _transactionScopeFixure; [TestFixtureSetUp] public void Init() { var transactionOptions = new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted,Timeout = TransactionManager.MaximumTimeout }; _transactionScopeFixure = new TransactionScope(TransactionScopeOption.required,transactionOptions); SetupAllDataForAllTest(); } [TestFixtureTearDown] public void FixtureTearDown() { _transactionScopeFixure.Dispose(); } public void SetupAllDataForAllTest() { // sql stuff here that will get undone from the TestFixtureTearDown scope dispose } [Test] public void DosqlStuff1() { // sql stuff here that will get undone from the TransactionBackedTest } [Test] public void DosqlStuff2() { // sql stuff here that will get undone from the TransactionBackedTest } }
想法是SetupAllDataForAllTest在开始时运行一次并插入测试依赖的所有基础数据.测试完成后,需要删除/回滚此基础数据.
我也希望每个测试都是隔离的,这样它们也不会互相干扰.
我现在遇到的问题是,在第一次测试之后,它表明TestFixture事务已经关闭,即使我只想让它关闭SetUp事务.我的假设是,如果你Dispose()和内部事务它会外部,所以我不知道如何完成我想做的事情
解决方法
您没有说出您使用的数据库.
在MS sql Server中,如果你在另一个事务中使用BEGIN TRANSACTION
(使它们嵌套)然后在嵌套事务中使用ROLLBACK TRANSACTION
,它将回滚所有内容(整个外部事务也是如此).
ROLLBACK TRANSACTION without a savepoint_name or transaction_name
rolls back to the beginning of the transaction. When nesting
transactions,this same statement rolls back all inner transactions to
the outermost BEGIN TRANSACTION statement.
为了能够仅回滚内部嵌套事务,它应该在SAVE TRANSACTION <name>
之前以嵌套事务的某个名称启动.然后你可以ROLLBACK< name>回滚只是嵌套的部分.
如果您正在使用其他数据库,则嵌套事务中的行为可能会有所不同.
我不知道如何使您的类发出正确的BEGIN或SAVE TRANSACTION sql语句,具体取决于事务是否嵌套.