C# 在单元测试中创建System.Web.Caching.Cache对象
我正在尝试为一个没有单元测试的项目中的函数实现一个单元测试,该函数需要System.Web.Caching.Cache对象作为参数。我一直在尝试使用代码创建此对象,例如C# 在单元测试中创建System.Web.Caching.Cache对象,c#,asp.net,C#,Asp.net,我正在尝试为一个没有单元测试的项目中的函数实现一个单元测试,该函数需要System.Web.Caching.Cache对象作为参数。我一直在尝试使用代码创建此对象,例如 System.Web.Caching.Cache cache = new System.Web.Caching.Cache(); cache.Add(...); …然后将“缓存”作为参数传入,但Add()函数导致NullReferenceException。到目前为止,我最好的猜测是,我无法在单元测试中创建这个缓存对象,需要从
System.Web.Caching.Cache cache = new System.Web.Caching.Cache();
cache.Add(...);
…然后将“缓存”作为参数传入,但Add()函数导致NullReferenceException。到目前为止,我最好的猜测是,我无法在单元测试中创建这个缓存对象,需要从HttpContext.Current.cache中检索它,而在单元测试中我显然无权访问它
如何对需要System.Web.Caching.Cache对象作为参数的函数进行单元测试?我认为最好的选择是使用模拟对象(查看Rhino mock)。当我遇到此类问题时(所讨论的类没有实现接口),最后,我常常围绕所讨论的类编写一个带有相关接口的包装器。然后在代码中使用包装器。对于单元测试,我手动模拟包装器并将自己的模拟对象插入其中 当然,如果模拟框架有效,那么就使用它。我的经验是,所有模拟框架在各种.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);
...
对遗留代码进行单元测试的一个非常有用的工具是。它将允许您完全绕过缓存对象,方法是告诉它模拟该类以及您发现有问题的任何方法调用。与其他mock框架不同,TypeMock使用反射来拦截那些方法调用,您可以让它为您进行mock,这样您就不必处理繁琐的包装 TypeMock是一种商业产品,但它有用于开源项目的免费版本。他们使用了一个“社区”版本,它是一个单用户许可证,但我不知道它是否仍然提供。
var-httpResponse=MockRepository.GenerateMock();
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);
var cache=MockRepository.GenerateMock();
Stub(x=>x.SetOmitVaryStar(true));
Stub(x=>x.Cache).Return(Cache);
Stub(x=>x.Response).Return(httpResponse);
httpContext.Response.Stub(x=>x.Cache).Return(Cache);
请更正问题中的拼写,以便人们更容易理解?Cachcing=Caching(不是想挑你的毛病,只是想帮忙)