2009-12-03 63 views
0

歡迎任何幫助。如何實現和測試ASP.NET MVC FakeRepository

我正在學習使用ASP.NET MVC框架編寫代碼,我對此概念進行了銷售。

我現在主要的絆腳石是如何設置和測試替換數據庫的存儲庫。爲了測試MVC應用程序,我創建了一個類並將其稱爲fakerepository.cs。此類實現IContactManagerRepository接口中的方法。

namespace MyTestMVCProject.Models 
{ 
    public class FakeContactManagerRepository : IContactManagerRepository 
    { 
     IList<Contact> _contacts = new List<Contact>(); 

     #region IContactManagerRepository Members 

     public Contact Create(Contact contact) 
     { 
      _contacts.Add(contact); 
      return contact; 
     } 

     public Contact Edit(Contact contact) 
     { 
      throw new NotImplementedException(); 
     } 

     public void Delete(int id) 
     { 
      throw new NotImplementedException(); 
     } 

     public IList<Contact> ListContacts() 
     { 
      return _contacts; 
     } 

     #endregion 
    } 
} 

在下面的嘗試測試中,我想確保聯繫人已創建,ID值是正確的。

[Test] 
public void Test_02_ContactController_Passes_ViewData_To_Details_View() 
{ 
    // Arrange 
    ContactController _controller = new ContactController(); 

    // Act 
    var _contact = new Contact 
    { 
     Id = 1, 
     FirstName = "Donald", 
     LastName = "Duck" 
    }; 

    var _result = _controller.Create(_contact) as ViewResult; 
    var contact = _result.ViewData.Model as Contact; 

    // Assert 
    Assert.AreEqual(1, _contact.Id); 
} 

不幸的是,測試總是失敗。

當然,我對測試很新,但我通過搜索谷歌並觀看ASP.NET MVC視頻,在短時間內找到了很多東西。

任何人都可以建議我如何測試一個fakerepository返回一個列表到ViewResult?

回答

2

測試可能看起來像:

[Test] 
public void PostingValidContactCreatesOneInRepositoryAndReturnsViewResult() 
{ 
    // Arrange 
    var controller = new ContactController(new FakeContactManagerRepository()); 

    // Act 
    var contact = new Contact 
    { 
     Id = 1, 
     FirstName = "Donald", 
     LastName = "Duck" 
    }; 

    var result = controller.Create(contact); 

    //Assert there is one created Contact in repository 
    Assert.AreEqual(1, Repository.ListContacts().Count()); 
    //Check if result is ViewResult 
    Assert.IsInstanceOfType(result,typeof(ViewResult)); 
    //Assert item Id is 1 
    Assert.AreEqual(1, Repository.ListContacts().First().ID); 
    //Check if posting valid contact doesn't invalidate model state 
    Assert.IsTrue(controller.ModelState.IsValid); 
} 

的ContactController必須採取IContactManagerRepository在構造

public ContactController(IContactManagerRepository repository); 

在測試中,你爲它提供FakeContactManagerRepository,在實際使用你可以注入你的真實信息庫。

編輯

你的錯誤是:

var contact = _result.ViewData.Model as Contact; 

發佈聯繫人不在_result.ViewData.Model,但在創建函數的參數。

var _result = _controller.Create(_contact) as ViewResult; 

這不是錯誤,但你可以這樣定義

var _result = _controller.Create(_contact) 

,檢查的結果是正確的類型。

Assert.AreEqual(1, _contact.Id); 

這沒有任何意義,您在_contact.Id之前分配了幾行。您應該從存儲庫中取出聯繫人並進行檢查。