1

I'm creating a unit test for a code that has an Item.Add method used and trying to use Sitecore Fake DB for this and I'm getting an error that it's not being populated.

A sample code below:

public class SampleTest
{
    [Fact]
    public void SampleTest_GetNewItem()
    {
        var myHomeID = new ID();
        var templateID = new ID();
        var template = new TemplateID(templateID);

        using (var db = new Db()
        {
            new DbItem("Home", myHomeID)
        }){
            Item myHomeItem = db.GetItem(myHomeID);
            Item returnItem = myHomeItem.Add("myNewItem", template);

            returnItem.Should().NotBeNull(); //Assert fails because returnItem is null
        }
    }
}

Is this behavior not supported by fake DB? or is there something wrong with the code? and how can the code be unit tested?

Thanks in advance! :)

2

You need to add template to the FakeDB database first.

Just add those 2 lines to your code:

var childTemplate = new DbTemplate("child", templateID);
db.Add(childTemplate);

e.g:

var myHomeID = new ID();
var templateID = new ID();
var template = new TemplateID(templateID);

using (var db = new Db {new DbItem("Home", myHomeID)})
{
    var childTemplate = new DbTemplate("child", templateID);
    db.Add(childTemplate);

    Item myHomeItem = db.GetItem(myHomeID);
    Item returnItem = myHomeItem.Add("myNewItem", template);

    returnItem.Should().NotBeNull();
}
  • Thank you! this works perfectly. I guess I didn't pay attention to the template being non-existent in the fake db. – qwert Jul 23 '18 at 11:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.