lundi 4 avril 2016

With Sitecore and FakeDB, how can you set a LookupField TargetItem?

With FakeDB, how can I set the value of the TargetItem in a DbLinkField?

The setup: I have a data template with a droplist that points to a list of other items.

I have a Sitecore Item extension method:

public static Item Lookup(this Item item, string fieldName)
{
    if (item == null) throw new ArgumentNullException("item");
    LookupField field = item.Fields[fieldName];
    if (field == null) return null;
    return field.TargetItem;
}

Unit Test and Result: When I run the following simple test against my code the LookupItem is found as a field, but the resulting LookupItem has a null TargetItem. Is it possible to mock this somehow using FakeDB?

[Test]
public void TestLookupItemExtension()
{
    ID templateId = ID.NewID;
    ID refItemId = ID.NewID;

    using (var db = new Db()
    {
        new DbTemplate("ItemTpl", templateId) { "Foo" },
        new DbItem("RefItem", refItemId),
        new DbItem("ItemComponent", ID.NewID, templateId)
        {
            new DbLinkField("Foo") { TargetID = refItemId  }
        }
    })
    {
        var item = db.GetItem("/sitecore/content/itemcomponent");
        var lookupItem = item.Lookup("Foo");
        lookupItem.Should().NotBeNull();
    }
}

The result of the field in the targetitem looks like this:

field   {Sitecore.Data.Fields.LookupField}  Sitecore.Data.Fields.LookupField
+       InnerField  "Foo"-{{C906FD3D-C5DA-4191-8F0A-F15603FB897E}}  Sitecore.Data.Fields.Field
+       TargetID    {{00000000-0000-0000-0000-000000000000}}    Sitecore.Data.ID
+       TargetItem  null    Sitecore.Data.Items.Item
        Value   "<link />"  string
+       _innerField "Foo"-{{C906FD3D-C5DA-4191-8F0A-F15603FB897E}}  Sitecore.Data.Fields.Field

So I'm getting the LookupField correct, but it's never actually putting the TargetId or TargetItem into the resulting LookupField mock object.

Any ideas would be appreciated.

Aucun commentaire:

Enregistrer un commentaire