c# - 如何从虚假网站获取 Sitecore 项目

标签 c# unit-testing sitecore

在单元测试中,我使用Sitecore.FakeDb

我已经扩展了示例以添加带有 rootPath 的 fakeSite,该 rootPath 已设置。 如果我尝试使用 Context.Site.GetItem(rootPath) 检索 rootItem,它将返回 null。

[Test]
public void FakeSite()
{
    // create a fake site context
    var fakeSite = new Sitecore.FakeDb.Sites.FakeSiteContext(
      new Sitecore.Collections.StringDictionary
        {
                { "name", "website" }, { "database", "web" }, { "rootPath", "/sitecore/content/NL" }
        });

    // switch the context site
    using (new Sitecore.Sites.SiteContextSwitcher(fakeSite))
    {
        var rootItem = Context.Site.Database.GetItem(Context.Site.RootPath); // returns null

        Assert.IsNotNull(rootItem);
        Assert.AreEqual("website", Sitecore.Context.Site.Name);
        Assert.AreEqual("master", Sitecore.Context.Site.Database.Name);
    }
}

我错过了什么?

最佳答案

您需要首先将假项目添加到您的假数据库中。

在此处查看来自 github 的示例代码:

public void HowToCreateSimpleItem()
{
  using (Sitecore.FakeDb.Db db = new Sitecore.FakeDb.Db
    {
      new Sitecore.FakeDb.DbItem("Home") { { "Title", "Welcome!" } }
    })
  {
    Sitecore.Data.Items.Item home = db.GetItem("/sitecore/content/home");
    Xunit.Assert.Equal("Welcome!", home["Title"]);
  }
}

public void HowToCreateHierarchyOfItems()
{
  using (Sitecore.FakeDb.Db db = new Sitecore.FakeDb.Db
    {
      new Sitecore.FakeDb.DbItem("Articles")
        {
          new Sitecore.FakeDb.DbItem("Getting Started"),
          new Sitecore.FakeDb.DbItem("Troubleshooting")
        }
    })
  {
    Sitecore.Data.Items.Item articles =
      db.GetItem("/sitecore/content/Articles");

    Xunit.Assert.NotNull(articles.Children["Getting Started"]);
    Xunit.Assert.NotNull(articles.Children["Troubleshooting"]);
  }
}

https://github.com/sergeyshushlyapin/Sitecore.FakeDb/wiki/Creating-a-Simple-Item

https://github.com/sergeyshushlyapin/Sitecore.FakeDb/wiki/Creating-a-Hierarchy-of-Items

关于c# - 如何从虚假网站获取 Sitecore 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41676683/

相关文章:

c# - 使用 ViewBag 中的列表选择 TagHelper

c# - morelinq 通过多个属性来区分

python - 如何在不修改代码的情况下禁用跳过pytest中的测试?

c# - 将字符串转换或显示为货币

c# - Visual Studio 2010 文档映射扩展

javascript - 有什么方法可以 stub 这些类型的函数吗?

unit-testing - 运行 SpecFlow 报告 - 错误 - 元素 <Target> 中的属性 "Label"无法识别

javascript - $scwhead 未在面向营销人员的 Sitecore Web 表单中定义

sitecore - Sitecore 6.4 中克隆项目之间的链接和引用

jquery - 完整日历小部件未显示在浏览器中