簡體   English   中英

使用Moq對LINQ to SQL CRUD操作進行單元測試

[英]Unit testing LINQ to SQL CRUD operations using Moq

我已經看過其他問題,但沒有什么能與我正在尋找的東西相提並論......主要是因為我不是100%肯定我正在尋找什么!

基本上我現在正在開發一個新項目,我已經為數據庫實體創建了抽象層,並將DAC設置為存儲庫。 我想用Mock對象對它進行單元測試,但是我已經用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. 放棄所有希望,因為我想要達到的目標是不可能的,而且我做錯了!

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

理想情況下,您會對這些進行一些集成測試,但如果您想對其進行單元測試,則可能有一些途徑,包括原始問題的評論中未提及的途徑。

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

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

使用Verify,您可以檢查參數是否是某個類型的某個參數,以及實際調用該方法的次數。

第二個。 或者,如果要驗證已在存儲庫集合中添加的實際對象,則可以在模擬上使用.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);

在您的實際示例中,您可以創建人員,然后將其添加到設置中。 在這里使用回調方法沒有用。

您還可以使用此技術增加變量以計算調用它的次數。

暫無
暫無

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

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