【问题标题】:Creating a System.Web.Caching.Cache object in a unit test在单元测试中创建 System.Web.Caching.Cache 对象
【发布时间】:2008-10-28 18:17:32
【问题描述】:

我正在尝试为没有单元测试的项目中的函数实现单元测试,并且该函数需要 System.Web.Caching.Cache 对象作为参数。我一直在尝试使用诸如...的代码来创建这个对象

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

...然后将“缓存”作为参数传入,但 Add() 函数会导致 NullReferenceException。到目前为止,我最好的猜测是,我无法在单元测试中创建此缓存对象,需要从 HttpContext.Current.Cache 中检索它,而我显然无法在单元测试中访问它。

如何对需要 System.Web.Caching.Cache 对象作为参数的函数进行单元测试?

【问题讨论】:

  • 能否请您更正问题中的拼写,以便人们更容易找到? Cachcing = 缓存(不是试图挑剔你或任何东西 - 只是想提供帮助)

标签: c# asp.net


【解决方案1】:

当我遇到这类问题(相关类没有实现接口)时,我通常会在相关类周围编写一个带有相关接口的包装器。然后我在我的代码中使用我的包装器。对于单元测试,我手动模拟包装器并将我自己的模拟对象插入其中。

当然,如果一个模拟框架有效,那么就使用它。我的经验是,所有模拟框架都存在与各种 .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);

...

【讨论】:

    【解决方案2】:

    我认为您最好的选择是使用模拟对象(查看 Rhino Mocks)。

    【讨论】:

      【解决方案3】:

      对遗留代码进行单元测试的一个非常有用的工具是TypeMock Isolator。它允许您通过告诉它模拟该类和您发现有问题的任何方法调用来完全绕过缓存对象。与其他模拟框架不同,TypeMock 使用反射来拦截您告诉它为您模​​拟的那些方法调用,因此您不必处理繁琐的包装器。

      TypeMock 一个商业产品,但它有免费的开源项目版本。他们过去有一个“社区”版本,它是一个单用户许可证,但我不知道是否仍然提供。

      【讨论】:

        【解决方案4】:
        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);
        

        【讨论】:

          猜你喜欢
          • 2017-12-11
          • 2010-12-16
          • 1970-01-01
          • 2014-04-24
          • 1970-01-01
          • 1970-01-01
          • 2014-06-16
          • 2011-08-23
          • 1970-01-01
          相关资源
          最近更新 更多