比方说,我有一个静态类,使用下面的扩展方法,它从缓存中检索文件或从磁盘读取文件,并将其放入缓存(如果它不存在)+对内容进行一些更改(例如,添加标记或属性):如何单元测试在剃刀视图中使用的静态方法?
public static class Foo
{
public static DoSomething(this HtmlHelper helper, string url, List<string> parameters)
{
string content = String.Empty;
var cache = HttpContext.Current.Cache[url];
if (cache == null)
{
string absolute_path = WebPages.HelperPage.Server.MapPath(url);
content = File.ReadAllText(absolute_path);
HttpContext.Current.Cache.Add(url, content, ...);
}
else
{
content = cache.ToString();
}
//make a few changes to content (e.g., add some tags or attributes)
content = makeChangesToContent(content, parameters);
return MvcHtmlString.Create(content);
}
}
此方法在这样的剃刀视图中使用:
@Html.DoSomething("/path/to/file", new List<string>(){"param1", "param2"});
为了使这一代码可测试我必须删除所有来自该方法的依赖关系。但由于它是静态的,在剃刀视图中使用,我不知道如何正确执行。
我唯一的选择就是使用Shims来伪造一些假方法的外部依赖关系。但是单元测试代码看起来有点沉重,运行需要大约200ms。
下面是单元测试的一个简单的例子:
[Test]
public void DoSomething_Should_Return_FileContent_From_Cache_When_It_Is_There()
{
string relativeFilePath = "/some/path";
string fileContent = "content";
string cachedKey = String.Empty;
object cachedValue = null;
using (ShimsContext.Create())
{
//Arrange
System.Web.Fakes.ShimHttpContext.CurrentGet =() =>
{
var httpContext = new System.Web.Fakes.ShimHttpContext();
httpContext.CacheGet =() =>
{
var cache = new System.Web.Caching.Fakes.ShimCache();
cache.ItemGetString = (key) =>
{
cachedKey = key;
cachedValue = fileContent;
return fileContent;
};
return cache;
};
return httpContext;
};
//Act
var result = helper.DoSomething(relativeFilePath, new List<string>(){"param1", "param2"});
//Assert
Assert.IsTrue(cachedKey.Equals(relativeFilePath));
Assert.IsTrue(cachedValue.Equals(fileContent));
}
它是测试它正确的方法是什么?有没有更好的选择? 从你的经验来看,测试这种静态方法的最佳方法是什么?
这可能会有所帮助 - http://stackoverflow.com/questions/4379450/mock-httpcontext-current-in-test-init-method – Carra
什么是您使用的Visual Studio版本? – zaitsman