2013-02-27 77 views
0

我有一個名爲「UserController」的控制器,名爲「Invite」。我的控制器有以下覆蓋方法:單元測試 - 用戶控制器的方法

DBRepository _repository; 
protected override void Initialize(System.Web.Routing.RequestContext requestContext) 
{ 
    base.Initialize(requestContext); 
      _repository = new DBRepository(); 

} 

因此,每次創建UserController類時都會調用此方法。

我的方法「邀請」有下面幾行:

var startTime = _repository.Get<AllowedTime>(p => p.TimeID == selectTimeStart.Value); 

,但是當我嘗試調用通過單位方法這個方法:

[TestMethod()] 
[UrlToTest("http://localhost:6001/")] 
public void InviteTest() 
{ 
    UserController target = new UserController(); // TODO: Initialize to an appropriate value 
    int? selectTimeStart = 57; 
    int? selectTimeEnd = 61; 
    Nullable<int> selectAttachToMeeting = new Nullable<int>(); // TODO: Initialize to an appropriate value 
    int InvitedUserID = 9; // TODO: Initialize to an appropriate value 
    UserInviteModel model = new UserInviteModel(); 
    model.Comment = "BLA_BLA_BLA"; 
    ActionResult expected = null; // TODO: Initialize to an appropriate value 
    ActionResult actual; 
    actual = target.Invite(selectTimeStart, selectTimeEnd, selectAttachToMeeting, InvitedUserID, model); 
    Assert.AreEqual(expected, actual); 
    Assert.Inconclusive("Verify the correctness of this test method."); 
} 

我得到一個錯誤「引用未設置。 ..「。我知道爲什麼會發生(_repository爲空,因爲在我的情況下未調用Initialize方法,但如何正確執行它?

回答

1

如果您希望DBRepository在測試期間從您的後備數據存儲區實際執行Get,改變你的_repository場是一個Lazy<DBRepository>,是被第一次使用時初始化。(我假設它是new在初始化方法編起來,而不是構造函數,因爲它依賴於當前請求上下文?)

如果您希望這是一個真正的單元測試,它不應該測試DBRepository類:你應該編程到一個你可以模擬的接口,另外,你需要使它成爲你的DBRepository來自某個地方,它可以由測試用例提供。您可以讓它由工廠構建或作爲單例提供,並且測試用例可以設置工廠或單例以提前提供模擬對象。但是,最好的方法是使用依賴注入,所以當你構造new UserController()時,你可以提供一個僞/模擬的IDBRepository。

+0

你能告訴我一個例子嗎? – 2013-02-27 01:18:57

+0

@ user285336:不幸的是,這是一個相當龐大的話題,在你的案例中的具體實現將取決於你的系統的細節超出了StackOverflow問題的範圍。我可以建議的最好的事情是花時間研究與單元測試有關的依賴注入和模仿。 – StriplingWarrior 2013-02-28 00:10:22