我正在尝试为没有单元测试的项目中的函数实现单元测试,并且该函数需要 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 对象作为参数的函数进行单元测试?
当我遇到此类问题(其中所涉及的类没有实现接口)时,我通常最终会围绕所涉及的类编写一个具有关联接口的包装器。然后我在代码中使用我的包装器。对于单元测试,我手动模拟包装器并将我自己的模拟对象插入其中。
当然,如果模拟框架有效,那么就使用它。我的经验是,所有模拟框架对于各种 .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);
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)