簡體   English   中英

在單元測試中創建System.Web.Caching.Cache對象

[英]Creating a System.Web.Caching.Cache object in a unit test

我正在嘗試為沒有單元測試的項目中的函數實現單元測試,並且此函數需要System.Web.Caching.Cache對象作為參數。 我一直試圖通過使用諸如......之類的代碼來創建這個對象。

System.Web.Caching.Cache cache = new System.Web.Caching.Cache();
cache.Add(...);

...然后將'cache'作為參數傳遞,但Add()函數導致NullReferenceException。 到目前為止,我最好的猜測是我不能在單元測試中創建這個緩存​​對象,需要從HttpContext.Current.Cache中檢索它,我顯然在單元測試中沒有訪問權限。

如何對需要System.Web.Caching.Cache對象作為參數的函數進行單元測試?

當我遇到這類問題時(所討論的類沒有實現接口),我經常最終編寫一個包含相關類的相關接口的包裝器。 然后我在我的代碼中使用我的包裝器。 對於單元測試,我手工模擬包裝器並將自己的模擬對象插入其中。

當然,如果模擬框架有效,那么請使用它。 我的經驗是,所有模擬框架都存在各種.NET類的問題。

public interface ICacheWrapper
{
   ...methods to support
}

public class CacheWrapper : ICacheWrapper
{
    private System.Web.Caching.Cache cache;
    public CacheWrapper( System.Web.Caching.Cache cache )
    {
        this.cache = cache;
    }

    ... implement methods using cache ...
}

public class MockCacheWrapper : ICacheWrapper
{
    private MockCache cache;
    public MockCacheWrapper( MockCache cache )
    {
        this.cache = cache;
    }

    ... implement methods using mock cache...
}

public class MockCache
{
     ... implement ways to set mock values and retrieve them...
}

[Test]
public void CachingTest()
{
    ... set up omitted...

    ICacheWrapper wrapper = new MockCacheWrapper( new MockCache() );

    CacheManager manager = new CacheManager( wrapper );

    manager.Insert(item,value);

    Assert.AreEqual( value, manager[item] );
}

真實的代碼

...

CacheManager manager = new CacheManager( new CacheWrapper( HttpContext.Current.Cache ));

manager.Add(item,value);

...

我認為你最好的選擇是使用模擬對象(查看Rhino Mocks)。

用於單元測試遺留代碼的非常有用的工具是TypeMock Isolator 它將允許您完全繞過緩存對象,告訴它模擬該類以及您發現有問題的任何方法調用。 與其他模擬框架不同,TypeMock使用反射攔截您告訴它為您模​​擬的方法調用,因此您不必處理繁瑣的包裝器。

TypeMock 一種商業產品,但它有開源項目的免費版本。 他們曾經有一個“社區”版本,這是一個單用戶許可證,但我不知道是否仍然提供。

var httpResponse = MockRepository.GenerateMock<HttpResponseBase>();
var cache = MockRepository.GenerateMock<HttpCachePolicyBase>();
   cache.Stub(x => x.SetOmitVaryStar(true));
   httpResponse.Stub(x => x.Cache).Return(cache);
   httpContext.Stub(x => x.Response).Return(httpResponse);
   httpContext.Response.Stub(x => x.Cache).Return(cache);

暫無
暫無

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

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