VS2005環境でのNAgile - TableDataGatewayを自前で実装するのは無駄 (-.-)

VS2005ではわざわざ自前でTableDataGatewayを書く必要が無い。データセットデザイナ上でTableAdapterを自動生成させれば良いから。

ってことで今日は自動生成したTableAdapterに対してどうやってユニットテストを書くかという考察。トランザクションロールバックさせてテストデータをクリアもしたい。

試行錯誤の結果として、テストメソッド毎にTransactionScopeを切ってTransactionScopeのCompleteメソッドを呼び出さずに強制ロールバックさせればいいのではという結論に達する。

以下はNorthwindのCategoriesテーブルに対して自動生成したCategoriesTableAdapterクラスのテストコード

[TestClass] 
public class TranzactionalTest 
{ 
 private CategoriesTableAdapter target_; 
 private NorthwindDataSet ds_; 

 [TestInitialize] 
 public void FillDataSet() 
 { 
  target_ = new CategoriesTableAdapter(); 
  ds_ = new NorthwindDataSet(); 
  target_.FillAll(ds_.Categories); 
 } 

 [TestMethod] 
 public void Insert() 
 { 
  using (TransactionScope ts = new TransactionScope()) 
  { 
   NorthwindDataSet.CategoriesRow category = 
    ds_.Categories.AddCategoriesRow("Test", "Description", null); 
   target_.Update(category); 

   NorthwindDataSet.CategoriesDataTable insertedCategories = 
    target_.GetDataByCategoryName("Test"); 

   Assert.AreEqual<int> (1, insertedCategories.Count); 
   Assert.AreEqual<string> ("Description", insertedCategories[0].Description); 
  } 
 } 
} 

修正点
TransactionScopeはTestInitializeで生成してTestCleanupでDisposeすればロールバックされる。

参考:NAgileで始める実践アジャイル開発 - 第3回 ソフトウェアの良い設計を行うコツ

よって上記コードはこう書くのが正解。

[TestClass] 
public class TranzactionalTest 
{ 
 private CategoriesTableAdapter target_; 
 private TransactionScope ts_;
 private NorthwindDataSet ds_; 

 [TestInitialize] 
 public void CreateTransactionScope() 
 { 
  ts_ = new TransactionScope();
  target_ = new CategoriesTableAdapter(); 
  ds_ = new NorthwindDataSet(); 
  target_.FillAll(ds_.Categories); 
 } 

 [TestCleanup]
 public void DisposeTransactionScope()
 {
  ts_.Dispose();
 }

 [TestMethod] 
 public void Insert() 
 { 
  NorthwindDataSet.CategoriesRow category = 
   ds_.Categories.AddCategoriesRow("Test", "Description", null); 
  target_.Update(category); 

  NorthwindDataSet.CategoriesDataTable insertedCategories = 
   target_.GetDataByCategoryName("Test"); 

  Assert.AreEqual<int> (1, insertedCategories.Count); 
  Assert.AreEqual<string> ("Description", insertedCategories[0].Description); 
 } 
}