簡體   English   中英

單元測試方法的IO操作的自定義回滾屬性

[英]Custom rollback attribute for IO operations for unit test methods

我具有測試方法的“回滾”屬性,用於測試使用數據庫事務的方法:

  public class RollbackAttribute : Attribute, ITestAction
  {
      private TransactionScope transaction;
      public void BeforeTest(TestDetails testDetails)
      {
          transaction = new TransactionScope();
      }

      public void AfterTest(TestDetails testDetails)
      {
          transaction.Dispose();
      }

      public ActionTargets Targets
      {
          get { return ActionTargets.Test; }
      }
  }

有什么方法可以為使用IO(創建文件夾)操作的方法創建類似的屬性?

在C#中,文件I / O實現未使用事務,因此您無法回滾它們。 您能做的最好的就是為此編寫自己的機制。

我不會復制其他文章,但是在這里您有一個有趣的示例,說明如何實現自己的事務存儲庫。

我發現帶有實現的nuget包更有趣: LINK

這里有用法示例:

// Wrap a file copy and a database insert in the same transaction
TxFileManager fileMgr = new TxFileManager();
using (TransactionScope scope1 = new TransactionScope())
{
    // Copy a file
    fileMgr.Copy(srcFileName, destFileName);

    // Insert a database record
    dbMgr.ExecuteNonQuery(insertSql);

    scope1.Complete();
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM