Automatically roll back your ling to sql integration tests

 原文地址:http://blog2.matthidinger.com/archive/2009/09/08/automatically-roll-back-your-linq-to-sql-integration-tests.aspx

今天我开始做MVC下数据部分的测试,开始的时候我试着搜索一些简单的测试linq部分的方法,因为在这一部分大多数情况会用到回滚,但最终我还是选择了自己写。我把它记录下来或许对一些人有帮助,这个基类是在微软的环境下写的但是在简单的修改后可以用到 nUnit,xUnit 等模式。

代码如下:

首先简单地继承这个基类,并通过内部Context属性进行更改测试类然后模拟自动回滚,每个测试都是如此。

 

/// <summary>
/// The base class will allow LINQ to SQL integration testing with automatic rollbacks after each test
/// </summary>
/// <typeparam name="TContext">The type of data context to use</typeparam>
public abstract class RolledBackDataContextTests<TContext> where TContext : DataContext
{
    private TContext _context;
    private DbTransaction _transaction;
 
    [TestInitialize]
    public void InitDataContext()
    {
        if(string.IsNullOrEmpty(ConnectionString))
        {
            _context = (TContext)Activator.CreateInstance(typeof(TContext));
        }
        else
        {
            _context = (TContext) Activator.CreateInstance(typeof (TContext), ConnectionString);
        }
 
        _context.Connection.Open();
        _transaction = _context.Connection.BeginTransaction();
        _context.Transaction = _transaction;
    }
 
    /// <summary>
    /// Provides access to the internal data context. Any changes made will be automatically rolled back
    /// </summary>
    protected TContext Context
    {
        get
        {
            if(_context == null)
                InitDataContext();
 
            return _context;
        }
    }
 
    /// <summary>
    /// Optionally specify the connection string to use
    /// </summary>
    protected virtual string ConnectionString
    {
        get
        {
            return null;
        }
    }

 

 
    [TestCleanup]
    public void TestCleanup()
    {
        _transaction.Rollback();
        _context.Dispose();
        _context = null;
    }
}

 

 

 

[TestClass]
public class SqlRepositoryTests : RolledBackDataContextTests<NorthwindDataContext>
{
    // Insert as many Products as required and then exercise your database integration Test Methods
    public void InsertProductToContext()
    {
        Product p = new Product { ProductName = "Temporary Product"};
        Context.Products.InsertOnSubmit(p);
        Context.SubmitChanges();
 
        // After each test ends, the transaction will be rolled back, and the new Product will not be in the database
    }
 
    [TestMethod]
    public void Test1()
    {
        // Test logic here
    }
}

发布了12 篇原创文章 · 获赞 3 · 访问量 9万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章