Search code examples
sitecoresitecore8sitecore-mvc

How to create layout field in sitecorefakedb?


How do you create a layout field using sitecore fakedb? I have the code below but it does not work.

The below code throws an error "the item is not a layout/rendering field"

var template = new Sitecore.FakeDb.DbTemplate("themes", Templates.SiteTheme.ID);

                var home = new Sitecore.FakeDb.DbItem("home", new Sitecore.Data.ID());                

                var lookUpField = new Sitecore.FakeDb.DbField("link", Templates.SiteTheme.Fields.SiteTheme) {
                    Type = "Rendering"
                };

                lookUpField.Value = home.ID.ToString();

                var site = new Sitecore.FakeDb.DbItem("site", new Sitecore.Data.ID(), Theming.Templates.SiteTheme.ID) {
                    lookUpField
                };          

                home.Add(site);

                db.Add(home);                

                var themesItem = db.GetItem("/sitecore/content/home/site");

               var layout = new LayoutField(themesItem.Fields["link"]);

                var value = layout.Value;

                Xunit.Assert.NotNull(value);

Solution

  • Something like that:

    [TestCase]
    public void FooLayout()
    {
        // arrange
        var itemId = ID.NewID;
        using (var db = new Db
        {
            new DbItem("Some Item", itemId)
            {
                new DbField(Sitecore.FieldIDs.LayoutField) { Value = "{presentation-xml}" }
            }
        })
        {
            var item = db.GetItem(itemId);
            // act
            // assert
            item[Sitecore.FieldIDs.LayoutField].Should().Be("{presentation-xml}");
        }
    }
    

    Note: Should().Be() methods come from https://www.nuget.org/packages/FluentAssertions/