我正在尝试为没有单元测试的项目中的函数实现单元测试,并且此函数需要System.Web.Caching.Cache对象作为参数.我一直试图通过使用诸如......之类的代码来创建这个对象.
System.Web.Caching.Cache cache = new System.Web.Caching.Cache();
cache.Add(...);
Run Code Online (Sandbox Code Playgroud)
...然后将'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] );
}
Run Code Online (Sandbox Code Playgroud)
真实的代码
...
CacheManager manager = new CacheManager( new CacheWrapper( HttpContext.Current.Cache ));
manager.Add(item,value);
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4644 次 |
| 最近记录: |