比方說,我有一個靜態類,使用下面的擴展方法,它從緩存中檢索文件或從磁盤讀取文件,並將其放入緩存(如果它不存在)+對內容進行一些更改(例如,添加標記或屬性):如何單元測試在剃刀視圖中使用的靜態方法?
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