c# – NUnit TestFixure和SetUp的嵌套TransactionScope

前端之家收集整理的这篇文章主要介绍了c# – NUnit TestFixure和SetUp的嵌套TransactionScope前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_502_1@我派生自这个基类,以便将每个单独的测试封装到一个回滚的事务中
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语句,具体取决于事务是否嵌套.

原文链接:https://www.f2er.com/csharp/99528.html

猜你在找的C#相关文章