当单元测试需要对数据库执行CRUD(Create,Retrieve,Update,Delete)操作时,测试过后会在我们的数据库中留下大量重复的垃圾数据,这些垃圾很碍眼不是吗?而且我们的下一个测试有可能因为这些垃圾产生一些错误。

那么我们要如何处理这些垃圾数据和保证测试的稳定的呢?显然,我们需要在每次测试之前和测试完成之后让数据库都保持相同的状态。换句话说,就是我们需要"undo"这些在测试中对数据库执行的CRUD操作。

对于我们需要的这种"undo"操作,你以前是怎么做的呢?手动的移除还是使用ADO.NET的事物处理呢?这些方法都可行,但对我们来说还不够好。因为它们都需要我们编写更多的代码,影响我们的开发效率。

现在,就要开始说本文的重点了,利用COM+的自动事务处理功能来帮助我们实现我们的"undo"。


Old Way

Use Com+ 1.5's new Transaction .The main advantage is that u don't need to strongly name the assemblies.

Among other things, COM+ 1.5 lets you use Enterprise Services without inheriting ServicedComponent explicitly with a feature called Services Without Components(SWC).

you need Windows® XP Service Pack 2 or Windows Server™ 2003 or later.

using System.EnterpriseServices;

public class TransactionalTests2005
{
    [SetUp]
    
public void Initialize()
    
{
        ServiceConfig config 
= new ServiceConfig();
        config.Transaction 
= TransactionOption.RequiresNew;
        ServiceDomain.Enter(config);
    }

    [Test]
    
public void UpdateCategoriesTest()
    
{
        
// Insert something into the database
    }

    [TearDown]
    
public void Cleanup()
    
{
        
if (ContextUtil.IsInTransaction)
        
{
            ContextUtil.SetAbort();
        }

        ServiceDomain.Leave();
    }

}

reference: MSDN Magizine
posted on 2008-04-03 17:22  Jason Hu  阅读(258)  评论(0编辑  收藏  举报