title: How to effectively test SiteCore LinkField
body: <p>I have been using moles to write unit tests on the hard to reach parts of my code – particularly where I use the types found in the sitecore class libraries (which are hard to use mocking frameworks with).  I have come across a surprisingly tricky problem where I’m trying to mole a LinkField type and test the following kind of code snippet.</p>
  
  <pre class="lang-cs prettyprint-override"><code>LinkField linkField = item.Fields["External Url"];
  
  if (linkField.IsInternal &amp;&amp; linkField.TargetItem != null)
  {
  // want to test this path
  </code></pre>
  
  <p>item.Fields is a field collection whose indexer returns a type of SiteCore.Data.Field, but LinkField is set up such that uses an implicit operator which hides the conversion which means you are able to work with an instance of LinkField in your code. </p>
  
  <p>My difficulty is that I cannot create a mole of type MLinkField, and assign this to the FieldCollection in the Item as it is strongly typed to Field.  Moreover, it seems that whilst I am able to create a type of MField, when the implicit conversion happens, it will work and return an object but none of the fields are set to have any values.  This means, I can’t test the code path above which relies on the state of the linkField being set a certain way.</p>
  
  <p>The only way I can think of setting these values is indirectly – i.e. finding what values need to be set by analysing the implicit conversion and setting these in MField.  The implicit operator calls the LinkField constructor as follows:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public LinkField(Field innerField) : base(innerField, "link")
  </code></pre>
  
  <p>which means I need to be conscious of how it instantiates the base type (XmlField), and in turn that class’s base type (CustomField).
  Then, to look at what underlying values TargetItem is looking for.  The end result is the need to mole out:  </p>
  
  <pre class="lang-cs prettyprint-override"><code>InnerField.Database.Items[internalPath];
  </code></pre>
  
  <p>Or</p>
  
  <pre class="lang-cs prettyprint-override"><code>InnerField.Database.Items[targetID];
  </code></pre>
  
  <p>Where InnerField is effectively my MField.</p>
  
  <p>Does anyone have a better idea?  This sounds horribly convoluted but I think that’s the nature of the beast with these assemblies.</p>