I am trying to run a unit test against a FakeDB setup using NUnit and Moq. The sitecore query is being abstracted through an interface which I'm Mocking. When I intially call the query it correctly creates the items with Field values. When the query results are used by the test method calling the repository - the field values all of the sudden go away.
I shortened the test and put it into this file. It has the bare minimum to run:
using System;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.FakeDb;
namespace NYL.UnitTests.FakeDB
{
[TestFixture]
public class FakeDbFieldValueTest
{
private readonly Mock<IRepository> _repo = new Mock<IRepository>();
private readonly ID _someItemTemplateId = ID.NewID;
[SetUp]
public void SetUp()
{
//database = FakeDatabase();
_repo.Setup(m => m.GetListOfItems()).Returns(Mock_GetListOfItems());
}
[Test]
public void Test_FakeDbFieldRetention()
{
// arrange
var items = _repo.Object.GetListOfItems();
// assert
items.Should().NotBeNull();
items.Should().HaveCount(3);
foreach (var item in items)
{
// Fields are null after passed back through mock
item.Fields["Some Field"].Should().NotBeNull();
item["Some Field"].Should().NotBeNullOrEmpty();
}
}
private IDisposable FakeDatabase()
{
return new Db
{
new DbItem("Home")
{
new DbItem("First Child", ID.NewID, _someItemTemplateId)
{
{"Some Field", "Value One"}
},
new DbItem("Second Child", ID.NewID, _someItemTemplateId)
{
{"Some Field", "Value Two"}
},
new DbItem("Third Child", ID.NewID, _someItemTemplateId)
{
{"Some Field", "Value Three"}
}
}
};
}
private Item[] Mock_GetListOfItems()
{
using (FakeDatabase())
{
var query = string.Format("fast:/sitecore/content/Home//*[@@templateid = '{0}']", _someItemTemplateId);
var items = Sitecore.Context.Database.SelectItems(query);
foreach (var item in items)
{
// Field Values render fine at creation
item.Fields["Some Field"].Should().NotBeNull();
item["Some Field"].Should().NotBeNullOrEmpty();
}
return items;
}
}
}
public interface IRepository
{
Item[] GetListOfItems();
}
}
The method Test_FakeDbFieldRetention
fails spectacularly with the fields being completely removed. In my comments you can see where the fields are found, so they are being set initially. However when passed through the repository interface they just disappear.
Can anyone help spot this error?