2011-09-29 99 views
4

我已經看了一下其他問題,但沒有真正匹配我所尋找的內容...主要是因爲我不是100%確定它是什麼正在尋找!單元測試使用Moq的LINQ to SQL CRUD操作

基本上我正在研究一個新項目,我爲DB實體創建了我的抽象層,並將DAC設置爲存儲庫。我想用單元測試此與模仿對象,但我已經打了帶有CRUD(特別是C)的操作,我的單元測試類智力牆:

[TestClass] 
public class RepositoryTest 
{ 
    private Mock<IPersonRepository> _repository; 
    private IList<IPerson> _personStore; 

    [TestInitialize()] 
    public void Initialize() 
    { 
     _personStore= new List<IPerson>() { 
      new Person() { Name = "Paul" }, 
      new Person() { Name = "John" }, 
      new Person() { Name = "Bob" }, 
      new Person() { Name = "Bill" }, 
     }; 

     _repository = new Mock<IPersonRepository>(); 
     _repository.Setup(r => r.Entirely()).Returns(_personStore.AsQueryable()); 
    } 

    [TestCleanup()] 
    public void Cleanup() 
    { 
     _personStore.Clear(); 
    } 

    [TestMethod()] 
    public void Can_Query_Repository() 
    { 
     IEnumerable<IPerson> people = _repository.Object.Entirely(); 
     Assert.IsTrue(people.Count() == 4); 
     Assert.IsTrue(people.ElementAt(0).Name == "Paul"); 
     Assert.IsTrue(people.ElementAt(1).Name == "John"); 
     Assert.IsTrue(people.ElementAt(2).Name == "Bob"); 
     Assert.IsTrue(people.ElementAt(3).Name == "Bill"); 
    } 

    [TestMethod()] 
    public void Can_Add_Person() 
    { 
     IPerson newPerson = new Person() { Name = "Steve" }; 

     _repository.Setup(r => r.Create(newPerson)); 

     // all this Create method does in the repository is InsertOnSubmit(IPerson) 
     // then SubmitChanges on the data context 
     _repository.Object.Create(newPerson); 

     IEnumerable<IPerson> people = _repository.Object.Entirely(); 
     Assert.IsTrue(people.Count() == 5); 
    } 
} 

我Can_Query_Repository方法是成功的,但是Can_Add_Person方法失敗斷言。現在,我需要做:

  1. 設置Mock存儲庫的.Create方法以將該元素添加到_personStore?
  2. 做類似的事嗎?
  3. 放棄所有希望,因爲我想達到的目標是不可能的,我做的一切都是錯誤的!

一如既往,任何幫助/建議表示讚賞!

+0

只是一個快速的評論來證明爲什麼我的存儲庫返回方法是完全()。我的存儲庫名稱是AllPeople,所以我可以在AllPeople.WhereAgeIs,AllPeople.WhereDOBIs和AllPeople.Entirely。 –

+1

您應該測試如果您正在模擬庫接口中添加/保存方法,而不是計數。 –

+0

你的意思是.Verify()方法嗎?我剛剛嘗試過,測試成功運行(如果我刪除了。Count()檢查)......這是什麼意思,這是否檢查方法的功能工作? –

回答

6

理想你會做那些一些集成測試,但如果你想單元測試,有可能途徑,包括未在原來的問題的意見中提到一個。

第一個。 測試你的crud時,你可以使用.Verify來檢查Create方法是否真的被調用。

mock.Verify(foo => foo.Execute("ping")); 

有了驗證,可以確認的說法是有一定的說法,某種類型的和時代的方法實際上是叫號。

第二個。 或者,如果您想驗證存儲庫集合中已添加的實際對象,則可以在模擬上使用.Callback方法。

在您的測試中創建一個列表,它將接收您創建的對象。 然後在您調用設置的同一行添加一個回調,它將在列表中插入創建的對象。

在您的斷言中,您可以檢查列表中的元素,包括它們的屬性以確保添加了正確的元素。

var personsThatWereCreated = new List<Person>(); 

_repository.Setup(r => r.Create(newPerson)).Callback((Person p) => personsThatWereCreated.Add(p)); 

// test code 
// ... 

// Asserts 
Assert.AreEuqal(1, personsThatWereCreated.Count()); 
Assert.AreEqual("Bob", personsThatWereCreated.First().FirstName); 

在您的實際示例中授予您創建人員然後將其添加到設置中。在這裏使用回調方法不會有用。

你也可以使用這種技術來增加一個變量來計算它被調用的次數。