2011-07-11 9 views
0

我試圖寫一個樣品NUnit的測試腳本來檢查值緩存NUnit的腳本來測試緩存數據

我寫的代碼像

[TestFixture] 

class Authorization 
{ 
    class AutherizationEntity 
    { 
     public int UserID { get; set; }   
     public int OperationCode { get; set; } 
     public bool permission { get; set; } 
    } 


    [SetUp] 
    public void Initialize() 
    { 

      //if (HttpContext.Current.Cache["UserRights"] == null) 
      //{ 
       List<AutherizationEntity> AuthorisationObject = new List<AutherizationEntity>(); 

       for (int i = 0; i < 5; i++) 
       { 
        AutherizationEntity AEntity = new AutherizationEntity(); 
        AEntity.OperationCode = 10; 
        AEntity.permission = true; 
        AEntity.UserID = i; 
        AuthorisationObject.Add(AEntity); 
       } 
       HttpContext.Current.Cache.Insert("UserRights", AuthorisationObject); //Here i am getting the exception in NUnit 
      //} 

    } 

    [TestCase] 
    public void AuthorizeUser() 
    {   
     int UserId = 1; 
     int OperationCode = 10;   
     Boolean HaveRight = false; 

     List<AutherizationEntity> AuthEntity = new List<AutherizationEntity>(); 
     AuthEntity = (List<AutherizationEntity>)HttpContext.Current.Cache.Get("UserRights"); 

     foreach (AutherizationEntity Auth in AuthEntity) 
     { 
      if ((Auth.UserID == UserId) && (Auth.OperationCode==OperationCode)) 
      { 
       HaveRight = Auth.permission; 
      } 
     } 

     Assert.AreEqual(HaveRight, true); 
    }  

} 

但是,當我試圖與運行腳本NUnit我收到一個異常

Authorization.AuthorizeUser(): SetUp:System.NullReferenceException:未將對象引用設置爲對象的實例。

你能幫我嗎?

回答

1

NUnit不會在Web上下文中運行,因此HttpContext.Current爲空。如果你想測試的話,你需要手動創建一個我們的上下文。

你可以爲你的httpcontext創建一個模擬類。請Google mock httpcontext,你會發現幾個可能對你有用的鏈接。

+0

感謝您的答覆..這可能是有益的,如果你能給我多一點的解釋還是一個有用的鏈接 – san

+0

@san:我沒有具體的樣品展示。我在我的帖子上建議可以幫助你的谷歌搜索。 –

+0

感謝克勞迪奧雷迪... – san

1

當測試綁定到HttpContext的代碼時,您必須依賴抽象並使用假的/存根的http上下文。有關該主題的更多信息,請參閱this question

不幸的是,緩存對象(和緩存類)不可能輕易地僞造,因爲它是一個密封的類。要走的路是在你的測試中創建一個包含Cache對象和僞/存根/模擬的相應接口的包裝類。

您可以在Web應用程序之外訪問Cache類,但在這種情況下,您可能不想這樣做。訪問緩存可以通過引用System.Web程序集並使用HttpRuntime類來完成。

using System.Web; 
using System.Web.Caching; 
… 
Cache cache = HttpRuntime.Cache; 
+0

謝謝...它的工作原理 – san