不幸的是,我不得不为一个遗留的 Sitecore MVC 代码库编写单元测试,其中调用了两个不同的 Sitecore 上下文。我知道这属于集成测试,但我没有选择在这方面教育我的项目领导。所以我选择使用FakeDb来模拟 Sitecore Instance 和NSubstitute来替代注入的依赖项(由于预算限制,不能使用任何 Profilier API 框架,如 MS Fakes、TypeMock 等)。我提供以下代码:
要进行单元测试的方法
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 上下文调用的总体上下文中运行我的单元测试?
任何帮助,将不胜感激。