c# - 在单元测试中创建 System.Web.Caching.Cache 对象

标签 c# asp.net

我正在尝试为没有单元测试的项目中的函数实现单元测试,并且此函数需要 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 对象作为参数的函数进行单元测试?

最佳答案

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

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

...

关于c# - 在单元测试中创建 System.Web.Caching.Cache 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/244280/

相关文章:

c# - 如果单个项目超出控件高度,WPF 列表框无法显示内容

c# - 尝试将图像保存到 Azure 服务器的文件系统中时出错 - GDI+ 中发生一般错误

javascript - 防止从 ASP NET 按钮关闭模式

javascript - 如何在 ASP.NET 中从前端 Javascript 函数调用后端 C# 函数

c# - 为特定页面和框架覆盖 web.config 中的 X-UA-Compatible 设置

java - 将 DeflaterInputStream 功能移植到 .net

c# - 检查打开的 Windows Media Player 文件的编码 UI 测试

c# - 使用来自 SignalR 的共享 IObservable

asp.net - 使用 Javascript 在浏览器中右键单击禁用“导出到 MS Excel”选项

c# - 如何停止“在关闭解决方案之前必须停止构建”