很遗憾,我必须为旧的Sitecore MVC代码库编写单元测试,在该代码库中调用了两个不同的Sitecore上下文。我知道这属于集成测试,但是我没有选择在那方面教育我的项目负责人。因此,我选择使用 FakeDb 来模拟Sitecore实例,并使用 NSubstitute 来代替注入的依赖项(由于预算限制,不能使用任何MS-Fake,TypeMock等Profilier API框架)。我正在提供以下代码:
要进行单元测试的方法
public bool DubiousMethod()
{
// This HttpContext call is pain area 1. This gets resolved when i call it using ItemContextSwitcher in Unit Tests.
string currentUrl = HttpContext.Current.Request.RawUrl;
// This Sitecore Context call to Site Name is pain area 2. This gets resolved when Unit Tests are run under SiteContextSwitcher.
string siteName = Sitecore.Context.Site.Name;
return true/False;
}
单元测试方法
[Fact]
public void DubiousMethodUT()
{
// create a fake site context
var fakeSite = new Sitecore.FakeDb.Sites.FakeSiteContext(
new Sitecore.Collections.StringDictionary
{
{ "name","website" },{ "database","web" },{ "rootPath","/sitecore/content/home" },{ "contentStartItem","home"},{"hostName","https://www.myorignalsiteurl.com"}
});
using (new Sitecore.Sites.SiteContextSwitcher(fakeSite))
{
//DubiousClassObject.DubiousMethod(home) // When Debugging after uncommenting this line i get correct value in **Sitecore.Context.Site.Name**
using (Sitecore.FakeDb.Db db = new Sitecore.FakeDb.Db
{
new Sitecore.FakeDb.DbItem("home") { { "Title","Welcome!" },new Sitecore.FakeDb.DbItem("blogs") }
})
{
Sitecore.Data.Items.Item home = db.GetItem("/sitecore/content/home");
//bool abc = confBlogUT.IsBlogItem(home);
using (new ContextItemSwitcher(home))
{
string siteName = Sitecore.Context.Site.Name;
var urlOptions = new Sitecore.Links.UrlOptions();
urlOptions.AlwaysIncludeServerUrl = true;
var pageUrl = Sitecore.Links.LinkManager.GetItemUrl(Sitecore.Context.Item,urlOptions);
HttpContext.Current = new HttpContext(new HttpRequest("",pageUrl.Substring(3),""),new HttpResponse(new StringWriter()));
Assert.False(DubiousClassObject.DubiousMethod(home); //When Debugging after commenting above DubiousMethodCall i get correct value for **HttpContext.Current.Request.RawUrl**
}
}
}
}
正如您所看到的,当我尝试从FakSiteContext调用该方法时,我为 Sitecore.Context.Site.Name 获取了正确的值,但是当 HttpContext.Current时我的代码中断了在该方法中调用.Request.RawUrl 。当我从 ContextItemSwitcher(FakeItem)上下文调用该方法时,情况恰好相反。到目前为止,我还没有找到一种方法来合并两个上下文(我认为这在Sitecore中是不可能的)。谁能建议我是否在一个可以控制fakeSite变量以及FakeItem上下文变量以及扩展其他Sitecore上下文调用的总体上下文中运行单元测试?
任何帮助将不胜感激。