I am trying to set up a simple test project to initially assert that my local C# models correspond to my Sitecore templates. The Item retrieval is successful using Database.GetItem(itemPath)
and I can inspect the item by debugging the test and can confirm that all Item.Fields
are present and contain the correct data. The field Item.HasClones
however contains an error:
'item.HasClones' threw an exception of type 'System.NullReferenceException'
I have debugged the same Item when running the live application and then HasClones is just false
so this only happens when getting the item in the test project.
When I attempt to read text from one of the fields using the FieldRenderer.Render
method it results in a System.NullReferenceException. I can access the text in the same field using item.Fields["Title"].Value.ToString();
without issue though.
I have tried getting around security using the SecurityDisabler
in case HasClones was somehow protected but no luck. I am not sure these two errors are connected but I have no idea how to confirm it. Have I missed something in the Context configuration or something like that? The same code runs fine in the main project (where Item is accessed using RenderingContext.Current.Rendering.Item
instead of with GetItem
) so does something else need initiating that I have missed?
Test code:
[SetUp]
public void SetUp()
{
State.HttpRuntime.AppDomainAppPath = TestContext.CurrentContext.TestDirectory;
Context.SetLanguage(Language.Parse("sv-SE"), true);
this.masterDb = Factory.GetDatabase("master");
}
[Test]
public void GetSomeBlockData_GetDataFromSitecore()
{
Item item;
string titleText;
using (new SecurityDisabler())
{
item = masterDb.GetItem("/sitecore/content/TestBlock");
bool hasClones = item.HasClones; // System.NullReferenceException: Object reference not set to an instance of an object.
titleTextOk = item.Fields["Title"].Value.ToString(); // This works fine
titleTextBroken = FieldRenderer.Render(item, "Title"); // System.NullReferenceException : Object reference not set to an instance of an object.
}
}
I am running: Sitecore.NET 8.2.170407, the project is using .NET 4.5.2. Testing framework is Nunit.
All the best //VA
EDIT:
I have investigated further and found that the issue with the FieldRenderer.Render
is that in the Render method it uses the class RenderFieldArgs
which in turn tries to check Context.Site.DisableWebEditEditing
when initiated. Context.Site is null so the method fails. I have tried to get Context working, mostly by following this guide but I can't get it working.