/ Umbraco

UmbracoExamine Y U use internal static

Just spent the evening trying to mock out a custom indexer extended from BaseUmbracoIndexer. I want to add the site to lucene documents so that news can be searched in the scope of a site.

I mocked out the dependencies for the new indexer, but then when the unit test ran it did not crash? What ‽

After snooping around in the source code I discovered that there was a method that is called before any work is done. This method (CanInitialize) “Returns true if the Umbraco application is in a state that we can initialize the examine indexes”. There was an attribute that I had never seen before on this method SecuritySafeCritical. As I did not want to spend hours now learning about this, I was glad to see that there was a Boolean flag to disable this check.

This is the point where I got very sad as I had poured about four hours into trying to work this out, the flag was an internal static field called DisableInitializationCheck, and I could not set it.

After copying the BaseUmbracoIndexer source code to a new type, I took a step back and decided this code duplication was not very nice.

I stopped and had a think, paced around for a bit and decided that Reflection might be able to help me, and after another 30 minutes I had worked it out (with some help from MSDN)
Here it is:

var fields = typeof(BaseUmbracoIndexer).GetFields(BindingFlags.NonPublic | BindingFlags.Static);
var disableInitializationCheckField = fields.SingleOrDefault(x => x.Name == "DisableInitializationCheck");
if (disableInitializationCheckField == null)
{
    Assert.Fail("Could Not Set DisableInitializationCheck");
}

disableInitializationCheckField.SetValue(null, true);

This is not ideal but sometimes you have to make sacrifices when you’re anal about TDD.