在单元测试创建的System.Web.Caching.Cache对象 [英] Creating a System.Web.Caching.Cache object in a unit test
问题描述
我想实现在一个没有单元测试项目中的功能单元测试,这功能需要的System.Web.Caching.Cache对象作为参数。我一直在尝试使用code,如...
I'm trying to implement a unit test for a function in a project that doesn't have unit tests and this function requires a System.Web.Caching.Cache object as a parameter. I've been trying to create this object by using code such as...
System.Web.Caching.Cache cache = new System.Web.Caching.Cache();
cache.Add(...);
...然后通过高速缓存作为参数,但Add()函数导致一个NullReferenceException。我最好的猜测到目前为止,我不能在单元测试创建该缓存对象,并需要从我显然不具备在一个单元测试访问HttpContext.Current.Cache检索。
...and then passing the 'cache' in as a parameter but the Add() function is causing a NullReferenceException. My best guess so far is that I can't create this cache object in a unit test and need to retrieve it from the HttpContext.Current.Cache which I obviously don't have access to in a unit test.
你怎么单元测试需要的System.Web.Caching.Cache对象作为参数的函数吗?
How do you unit test a function that requires a System.Web.Caching.Cache object as a parameter?
推荐答案
当我一直面临着这样的问题(其中有问题的类没有实现一个接口),我经常写出来与包装有关类别各地相关的接口。然后,我用我的包装在我的code。单元测试,我用手模拟包装,并插入我自己的模仿对象进去。
When I've been faced with this sort of problem (where the class in question doesn't implement an interface), I often end up writing a wrapper with associated interface around the class in question. Then I use my wrapper in my code. For unit tests, I hand mock the wrapper and insert my own mock object into it.
当然,如果一个模拟框架的工作,然后用它来代替。我的经验是,所有嘲弄框架有各种.NET类的一些问题。
Of course, if a mocking framework works, then use it instead. My experience is that all mocking frameworks have some issues with various .NET classes.
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] );
}
皇家code
...
CacheManager manager = new CacheManager( new CacheWrapper( HttpContext.Current.Cache ));
manager.Add(item,value);
...
这篇关于在单元测试创建的System.Web.Caching.Cache对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!