【问题标题】:Unit Testing the Use of TransactionScope对 TransactionScope 的使用进行单元测试
【发布时间】:2009-03-09 15:50:44
【问题描述】:

序言: 我设计了一个强接口且完全可模拟的数据层类,当多个调用应包含在单个事务中时,它期望业务层创建一个TransactionScope。

问题:我想对我的业务层使用TransactionScope 对象进行单元测试。

不幸的是,使用TransactionScope 的标准模式如下:

using(var scope = new TransactionScope())
{
    // transactional methods
    datalayer.InsertFoo();
    datalayer.InsertBar();
    scope.Complete();
}

虽然就程序员的可用性而言,这是一个非常棒的模式,但测试它是否完成似乎……对我来说是不可能的。我无法检测到瞬态对象已被实例化,更不用说模拟它以确定对其调用了方法。然而,我的报道目标意味着我必须这样做。

问题:我如何构建单元测试以确保TransactionScope 按照标准模式正确使用?

最后的想法:我考虑过一个肯定会提供我需要的覆盖范围的解决方案,但拒绝了它,因为它过于复杂且不符合标准 TransactionScope 模式。它涉及在我的数据层对象上添加一个CreateTransactionScope 方法,该方法返回一个TransactionScope 的实例。但是因为 TransactionScope 包含构造函数逻辑和非虚拟方法,因此即使不是不可能模拟也很困难,CreateTransactionScope 将返回一个 DataLayerTransactionScope 的实例,这将是 TransactionScope 的一个可模拟外观。

虽然这可能会完成这项工作,但它很复杂,我更喜欢使用标准模式。有没有更好的办法?

【问题讨论】:

  • 非常感谢您的宝贵答复!我有一个问题。我可以将它与 ES DB (NoSQL) 一起使用吗?

标签: c# .net unit-testing transactions


【解决方案1】:

我现在正面临同样的问题,对我来说似乎有两种解决方案:

  1. 不要解决问题。
  2. 为遵循相同模式但可模拟/可存根的现有类创建抽象。

编辑: 我现在为此创建了一个 CodePlex 项目:http://legendtransactions.codeplex.com/

我倾向于创建一组用于处理事务的接口和一个委托给 System.Transaction-implementations 的默认实现,例如:

public interface ITransactionManager
{
    ITransaction CurrentTransaction { get; }
    ITransactionScope CreateScope(TransactionScopeOption options);
}

public interface ITransactionScope : IDisposable
{
    void Complete();  
}

public interface ITransaction
{
    void EnlistVolatile(IEnlistmentNotification enlistmentNotification);
}

public interface IEnlistment
{ 
    void Done();
}

public interface IPreparingEnlistment
{
    void Prepared();
}

public interface IEnlistable // The same as IEnlistmentNotification but it has
                             // to be redefined since the Enlistment-class
                             // has no public constructor so it's not mockable.
{
    void Commit(IEnlistment enlistment);
    void Rollback(IEnlistment enlistment);
    void Prepare(IPreparingEnlistment enlistment);
    void InDoubt(IEnlistment enlistment);

}

这似乎需要做很多工作,但另一方面,它是可重复使用的,而且这一切都非常容易测试。

请注意,这并不是接口的完整定义,足以让您了解全局。

编辑: 我只是做了一些快速而肮脏的实现作为概念证明,我认为这是我将采取的方向,这就是我到目前为止提出的。我在想也许我应该为此创建一个 CodePlex 项目,这样问题就可以一劳永逸地解决。这不是我第一次遇到这种情况。

public interface ITransactionManager
{
    ITransaction CurrentTransaction { get; }
    ITransactionScope CreateScope(TransactionScopeOption options);
}

public class TransactionManager : ITransactionManager
{
    public ITransaction CurrentTransaction
    {
        get { return new DefaultTransaction(Transaction.Current); }
    }

    public ITransactionScope CreateScope(TransactionScopeOption options)
    {
        return new DefaultTransactionScope(new TransactionScope());
    }
}

public interface ITransactionScope : IDisposable
{
    void Complete();  
}

public class DefaultTransactionScope : ITransactionScope
{
    private TransactionScope scope;

    public DefaultTransactionScope(TransactionScope scope)
    {
        this.scope = scope;
    }

    public void Complete()
    {
        this.scope.Complete();
    }

    public void Dispose()
    {
        this.scope.Dispose();
    }
}

public interface ITransaction
{
    void EnlistVolatile(Enlistable enlistmentNotification, EnlistmentOptions enlistmentOptions);
}

public class DefaultTransaction : ITransaction
{
    private Transaction transaction;

    public DefaultTransaction(Transaction transaction)
    {
        this.transaction = transaction;
    }

    public void EnlistVolatile(Enlistable enlistmentNotification, EnlistmentOptions enlistmentOptions)
    {
        this.transaction.EnlistVolatile(enlistmentNotification, enlistmentOptions);
    }
}


public interface IEnlistment
{ 
    void Done();
}

public interface IPreparingEnlistment
{
    void Prepared();
}

public abstract class Enlistable : IEnlistmentNotification
{
    public abstract void Commit(IEnlistment enlistment);
    public abstract void Rollback(IEnlistment enlistment);
    public abstract void Prepare(IPreparingEnlistment enlistment);
    public abstract void InDoubt(IEnlistment enlistment);

    void IEnlistmentNotification.Commit(Enlistment enlistment)
    {
        this.Commit(new DefaultEnlistment(enlistment));
    }

    void IEnlistmentNotification.InDoubt(Enlistment enlistment)
    {
        this.InDoubt(new DefaultEnlistment(enlistment));
    }

    void IEnlistmentNotification.Prepare(PreparingEnlistment preparingEnlistment)
    {
        this.Prepare(new DefaultPreparingEnlistment(preparingEnlistment));
    }

    void IEnlistmentNotification.Rollback(Enlistment enlistment)
    {
        this.Rollback(new DefaultEnlistment(enlistment));
    }

    private class DefaultEnlistment : IEnlistment
    {
        private Enlistment enlistment;

        public DefaultEnlistment(Enlistment enlistment)
        {
            this.enlistment = enlistment;
        }

        public void Done()
        {
            this.enlistment.Done();
        }
    }

    private class DefaultPreparingEnlistment : DefaultEnlistment, IPreparingEnlistment
    {
        private PreparingEnlistment enlistment;

        public DefaultPreparingEnlistment(PreparingEnlistment enlistment) : base(enlistment)
        {
            this.enlistment = enlistment;    
        }

        public void Prepared()
        {
            this.enlistment.Prepared();
        }
    }
}

这是一个依赖于 ITransactionManager 来处理其事务性工作的类的示例:

public class Foo
{
    private ITransactionManager transactionManager;

    public Foo(ITransactionManager transactionManager)
    {
        this.transactionManager = transactionManager;
    }

    public void DoSomethingTransactional()
    {
        var command = new TransactionalCommand();

        using (var scope = this.transactionManager.CreateScope(TransactionScopeOption.Required))
        {
            this.transactionManager.CurrentTransaction.EnlistVolatile(command, EnlistmentOptions.None);

            command.Execute();
            scope.Complete();
        }
    }

    private class TransactionalCommand : Enlistable
    {
        public void Execute()
        { 
            // Do some work here...
        }

        public override void Commit(IEnlistment enlistment)
        {
            enlistment.Done();
        }

        public override void Rollback(IEnlistment enlistment)
        {
            // Do rollback work...
            enlistment.Done();
        }

        public override void Prepare(IPreparingEnlistment enlistment)
        {
            enlistment.Prepared();
        }

        public override void InDoubt(IEnlistment enlistment)
        {
            enlistment.Done();
        }
    }
}

【讨论】:

  • 我害怕那个。告诉我,你如何处理捕获 TransactionScope 的实例化?您是否通过某种形式的工厂强制实例化并模拟工厂以发出模拟的 TransactionScope?
  • 本例中的 ITransactionManager 就是那个工厂,它具有 CreateScope 方法。这是一项服务,我将根据事务处理将其注入到类中,或者可以使用服务定位器。
  • 嘿,我刚刚偶然发现了你的编辑。 LegendTransactions 看起来很棒!
  • 我认为你做得很好......我一定会检查你在 codeplex 上的工作......奇怪的是 MS 人没有把它放在他们的框架中......
  • 拜托,任何使用 IEnlistmentNotification 的好示例代码?谢谢。
【解决方案2】:

忽略这个测试好不好......

非常肮脏的 hack 是检查 Transaction.Current 不为空。

这不是一个 100% 的测试,因为有人可能会使用 TransactionScope 以外的东西来实现这一点,但它应该防止明显的“没有费心进行事务”部分。

另一种选择是故意尝试创建一个新的 TransactionScope,其隔离级别与将/应该使用的任何东西和TransactionScopeOption.Required 不兼容。如果这成功而不是抛出 ArgumentException 则没有事务。这需要您知道某个特定的 IsolationLevel 未被使用(像 Chaos 之类的东西是一个潜在的选择)

这两个选项都不是特别令人愉快,后者非常脆弱并且受 TransactionScope 语义保持不变的影响。我会测试前者而不是后者,因为它更健壮(并且易于阅读/调试)。

【讨论】:

  • 我可能会卡在做空检查;不过,我希望还有其他选择。关于测试是不是一件好事……你能提供你的意见吗?您认为我不应该费心确定是否创建了交易吗?还是你不同意嘲笑的欲望?
  • 这不是嘲讽。这是这个api的消费者使用事务的坚持。对于单个查询,不需要显式事务。如果它导致 DTM 启动,它也可能会给人们带来问题(我遭受的痛苦)
  • 我也会警惕这个测试是否是一种虚假的安全感。处理需要交易以确保正确性的事情很困难。仅仅有一笔交易可能还不够……
【解决方案3】:

我找到了一种使用 Moq 和 FluentAssertions 进行测试的好方法。假设您的被测单元如下所示:

public class Foo
{
    private readonly IDataLayer dataLayer;

    public Foo(IDataLayer dataLayer)
    {
        this.dataLayer = dataLayer;
    }

    public void MethodToTest()
    {
        using (var transaction = new TransactionScope())
        {
            this.dataLayer.Foo();
            this.dataLayer.Bar();
            transaction.Complete();
        }
    }
}

您的测试将如下所示(假设为 MS 测试):

[TestClass]
public class WhenMethodToTestIsCalled()
{
    [TestMethod]
    public void ThenEverythingIsExecutedInATransaction()
    {
        var transactionCommitted = false;
        var fooTransaction = (Transaction)null;
        var barTransaction = (Transaction)null;

        var dataLayerMock = new Mock<IDataLayer>();

        dataLayerMock.Setup(dataLayer => dataLayer.Foo())
                     .Callback(() =>
                               {
                                   fooTransaction = Transaction.Current;
                                   fooTransaction.TransactionCompleted +=
                                       (sender, args) =>
                                       transactionCommitted = args.Transaction.TransactionInformation.Status == TransactionStatus.Committed;
                               });

        dataLayerMock.Setup(dataLayer => dataLayer.Bar())
                     .Callback(() => barTransaction = Transaction.Current);

        var unitUnderTest = new Foo(dataLayerMock.Object);

        unitUnderTest.MethodToTest();

        // A transaction was used for Foo()
        fooTransaction.Should().NotBeNull();

        // The same transaction was used for Bar()
        barTransaction.Should().BeSameAs(fooTransaction);

        // The transaction was committed
        transactionCommitted.Should().BeTrue();
    }
}

这非常适合我的目的。

【讨论】:

    【解决方案4】:

    我是一名 Java 开发人员,因此我不确定 C# 的细节,但在我看来,您需要在这里进行两个单元测试。

    第一个应该是成功的“蓝天”测试。您的单元测试应确保事务提交后所有 ACID 记录都出现在数据库中。

    第二个应该是“古怪”的版本,它执行 InsertFoo 操作,然后在尝试 InsertBar 之前抛出异常。成功的测试将表明异常已被抛出,并且 Foo 和 Bar 对象都没有提交到数据库。

    如果这两个都通过,我会说您的 TransactionScope 正在正常工作。

    【讨论】:

    • 不幸的是,我不打算对系统的这一部分进行集成测试;在我的单元测试期间,数据层将被模拟,并且不会发生与数据库的连接。我可以测试我期望的各种方法调用是否发生;我担心的是是否创建了TransactionScope。
    • 本质上,我想要可重复的单元测试,我可以经常快速地进行;测试是否插入了一行不会为我剪掉它。不过谢谢你的回复! :)
    • 我认为它可重复且足够快——这只是我的看法。这似乎非常具有确定性——一个会成功,另一个不会。这不是真正的持久性测试,而是服务层测试。数据库不会被模拟,但如果我这样做,服务层就会被模拟。
    • 我知道你来自哪里,但我认为这不符合我的问题。我已经进行了集成测试,可以对我的数据层进行满意的测试。我现在希望unit 测试我的业务层对数据层的use。我不希望通过集成测试来做到这一点
    • 再次,我明白你在说什么,如果情况不同,我可能会这样做,但不幸的事实是(出于各种官僚原因)我无法针对实际数据库运行此测试。我必须模拟没有连接。
    【解决方案5】:

    在自己考虑过同样的问题后,我得出了以下解决方案。

    将模式更改为:

    using(var scope = GetTransactionScope())
    {
        // transactional methods
        datalayer.InsertFoo();
        datalayer.InsertBar();
        scope.Complete();
    }
    
    protected virtual TransactionScope GetTransactionScope()
    {
        return new TransactionScope();
    }
    

    当你需要测试你的代码时,你继承了被测类,扩展了函数,所以你可以检测它是否被调用。

    public class TestableBLLClass : BLLClass
        {
            public bool scopeCalled;
    
            protected override TransactionScope GetTransactionScope()
            {
                this.scopeCalled = true;
                return base.GetTransactionScope();
            }
        }
    

    然后,您在类的可测试版本上执行与 TransactionScope 相关的测试。

    【讨论】:

    • 单元测试样本?
    • 没有样本,但我只是照常调用函数,然后验证 scopeCalled 布尔值是否为真
    猜你喜欢
    • 1970-01-01
    • 2012-01-08
    • 2020-03-07
    • 2017-11-22
    • 2010-10-14
    • 2014-02-20
    • 2020-05-01
    • 1970-01-01
    • 2013-08-10
    相关资源
    最近更新 更多