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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章