2017-01-16 27 views
2

在單元測試中,我使用的是Sitecore.FakeDb如何從假網站獲取Sitecore項目

我已經擴展了樣本以添加帶有rootPath的fakeSite,它被設置。 如果我嘗試使用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); 
    } 
} 

我在想什麼?

+0

感謝編輯@ marek-musielak –

回答

3

您需要先將假項添加到您的假數據庫中。從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

+0

聽起來不錯,當然。我已經使用過了,現在我正試圖將這兩者結合起來。 –

0

正如@Marek說,我沒有創建一個項目,只需設置ROOTPATH哪一個項目它應該點。

這是工作測試。

[Test] 
    public void FakeSite() 
    { 
     using (Db db = new Db("web") 
     { 
      new DbItem("NL") { { "Title", "NL Site" } } 
     }) 
     { 
      Item siteItem = db.GetItem("/sitecore/content/NL"); 

      // 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)) 
      { 
       Assert.AreEqual("website", Sitecore.Context.Site.Name); 
       Assert.AreEqual("web", Sitecore.Context.Site.Database.Name); 

       var rootItem = Context.Site.Database.GetItem(Context.Site.RootPath); 
       Assert.IsNotNull(rootItem); 
      } 
     } 
    } 

雖然我意識到網站是指CM/CD網站。不是我正在尋找的MultiSite。