Archive

Posts Tagged ‘TDD’

Sitecore Fakes Media Items LinkFields and a challange.

13/06/2013 Leave a comment

When I  first started building the Sitecore Fakes Isolation framework I was given a challenge by Per Bering. The challenge was  to make the following unit test pass.


MediaManager.GetMediaUrl((MediaItem)((LinkField)contenItem.Fields["Thumbnail"]).TargetItem).ShouldAllBeEquivalentTo("/~/media/hello.png");

Passing this test would require for implementation of some more fake objects in existing Sitecore Fakes Framework,  a implementation for easily adding LinkField XML to an field “General Link Field in this case” ,  make the mapping to the TargetItem And create it. Creating a fake media Item, and replacing the default Media Provider used by the MediaManager.

The Fake Intenal Link Field, builds the XML required for casting in to the real LinkField, so it derives from a FakeField which build the XML allmost like Sitecore Does it.

Here is the FakeField and FakeLinkField no getters is placed on the FakeLinkField since I expected values to be fetch through the regular LinkField.

FAKEFIELD:

public class FakeField
 {
 public FakeField(string xmlString)
 {
 XMLDocument = XmlUtil.LoadXml(xmlString);
 }

 public void SetAttribute(string name, string value)
 {
 XmlUtil.SetAttribute(name, "", value, XMLDocument.FirstChild);
 }

public XmlDocument XMLDocument;
 }

FAKELINKFIELD

public class FakeInternalLinkField : FakeLinkField
 {
 public FakeInternalLinkField(Item itemToLinkTo,string target="",string url = "", string text="", string anchor="",string querystring="" ,string title="" ,string cssclass="")
 {
 SetLinkToItem(itemToLinkTo);
 Target = target;
 Url = url;
 Text = text;
 Anchor = anchor;
 QueryString = querystring;
 Title = title;
 Class = cssclass;
 LinkType = "internal";
 }

private void SetLinkToItem(Item itemToLinkTo)
 {
 ((FakeDatabase) Factory.GetDatabase(itemToLinkTo.Database.Name)).FakeAddItem(itemToLinkTo);
 TargetItem = itemToLinkTo;
 }

public override string ToString()
 {
 return XMLDocument.InnerXml;
 }
 }

When adding the  FakeLinkField to an field on a FakeItem simply call the .ToString() and build the XML for a regular LinkField from Sitecore. See Example below.

[Fact]
 public void Field_AddingLinkFieldWithLinkFromOneItemToAnother_TargetItemShouldReturnLinkedToItem()
 {
 Item linkedToItem = new FakeItem();
 FakeInternalLinkField fakeLinkField = new FakeInternalLinkField(linkedToItem);

 ID fieldId = ID.NewID;
 FieldList fieldCollection = new FieldList();
 fieldCollection.Add(fieldId,fakeLinkField.ToString());

Item itemToLinkFrom = new FakeItem(fieldCollection);

LinkField sitecoreLinkField = (LinkField) itemToLinkFrom.Fields[fieldId];

 sitecoreLinkField.TargetItem.ID.ShouldBeEquivalentTo(linkedToItem.ID);
 }

With that in place the inner part of challenges is now passing.

Next was the TypeCast to a MedaiItem, again creating a FAkeMedia Item ad mapping all the field passed in all most does the job. BUT sitecore asks for field values using their names so an additional mapping from id to field named is required, Sitecore Fakes now mappes most of the standard field on an imageItem from Sitecore using the MediaField setting file se both below.

public class FakeMediaItem : MediaItem
 {
 private readonly MediaStandardFields _mediaStandardFields;
 public FakeMediaItem(string name = "" ,string filepath="", string alt="", string width="",string height="",string title="",string keywords="",string extension="",string mimetype="",string size="" ) :
 base(CreateDataItem(name,filepath,alt,width,height,title,keywords,extension,mimetype,size))
 {
 _mediaStandardFields = new MediaStandardFields();
 }

private static Item CreateDataItem(string name,string filepath, string alt, string width, string height, string title, string keywords, string extension, string mimetype, string size)
 {
 FieldList fieldList = CreateFieldList(filepath, alt, width, height, title, keywords, extension, mimetype, size);
 FakeItem dataItem = new FakeItem(fieldList,name);

 AddMediaItemFieldMappings(dataItem);

 return dataItem;
 }

private static FieldList CreateFieldList(string filepath, string alt, string width, string height, string title,
 string keywords, string extension, string mimetype, string size)
 {
 FieldList fieldList = new FieldList();

fieldList.Add(MediaStandardFields.FilePathId, filepath);
 fieldList.Add(MediaStandardFields.AltId, alt);
 fieldList.Add(MediaStandardFields.WidthId, width);
 fieldList.Add(MediaStandardFields.HeightId, height);
 fieldList.Add(MediaStandardFields.TitleId, title);
 fieldList.Add(MediaStandardFields.KeywordsId, keywords);
 fieldList.Add(MediaStandardFields.ExtensionId, extension);
 fieldList.Add(MediaStandardFields.MimetypeId, mimetype);
 fieldList.Add(MediaStandardFields.SizeId, size);
 return fieldList;
 }



And the FieldMappings

 public class MediaStandardFields
 {
 public static ID FilePathId = ID.NewID;
 public static ID AltId = ID.NewID;
 public static ID WidthId = ID.NewID;
 public static ID HeightId = ID.NewID;
 public static ID TitleId = ID.NewID;
 public static ID KeywordsId = ID.NewID;
 public static ID ExtensionId = ID.NewID;
 public static ID MimetypeId = ID.NewID;
 public static ID SizeId = ID.NewID;
 public static string FilePath = "file path";
 public static string Alt = "Alt";
 public static string Width = "Width";
 public static string Height = "Height";
 public static string Title = "Title";
 public static string Keywords = "Keywords";
 public static string Extension = "Extension";
 public static string Mimetype = "Mime type";
 public static string Size = "size";

public MediaStandardFields()
 {
 }
 }

Now missing is the replacement for the fake media provide switching is fairly easy but changing in the app.config file


<mediaLibrary>
 <mediaProvider type="Sitecore.Fakes.FakeMediaProvider, Sitecore.Fakes" />
 </mediaLibrary>

Since this is a first release and to make the test pass with out writting to much code I’m gonna give the premise that and media url is build from the item name and the type extesion , prefixed with “/~/media library/”. Here is is rather simple implementation of the Fake Media Provider.

 public class FakeMediaProvider : MediaProvider
 {
 public override string GetMediaUrl(MediaItem item)
 {
 Item sourceItem = item;
 return String.Format("/~/media/{0}.{1}", sourceItem.Name, sourceItem[MediaStandardFields.ExtensionId]);
 }
 }

And Now Lets See the “unit test” / challenge pass.

[Test]
 public void The_Per_Bering_Challnange()
 {
 MediaItem mediaItem = new FakeMediaItem("hello",extension:"png");

ID linkFieldId = ID.NewID;
 FakeInternalLinkField fakeLinkField = new FakeInternalLinkField(mediaItem);

FieldList fieldList = new FieldList();
 fieldList.Add(linkFieldId, fakeLinkField.ToString());

 FakeItem contenItem= new FakeItem(fieldList);

 MediaManager.GetMediaUrl((MediaItem)((LinkField)contenItem.Fields[linkFieldId]).TargetItem).ShouldAllBeEquivalentTo("/~/media/hello.png");
 }

13-06-2013 13-14-53

Remember unlike other Sitecore unit testing examples this is all done i memory.  So this is pure unit testing no integration testing. And hopefully  Sitecore Fakes will develope over timer to support more features. Let me know which feature I should work on next.

Advertisements

Introducing Sitecore Fakes

07/06/2013 2 comments

Mocking Sitecore recently became a lot easier with Microsoft Fakes in Vs 2012 update 2 or by using Typemock. Lately I’ve started using NCrunh and yes it might be a bit overpriced but it is worth every penny, at least for me. I know Typmock work with NCrunch but that comes with an even larger price tag, and unfortunately Microsoft fakes doesn’t work “yet” with NCrunch, so I’m back to my Sitecore Test Item Orginal Post.

Earlier I showed how to stub out field data with the sitecore test item. With the test item you can cover the most basic data transfer stuff from Sitecore through the field collection. But I really wanted to do more complex testing without talking to the database or doing integrationtest. Mike Edwards showed a solution where you copy  sections from the web.config to a local app.config in your test project. By doing that you are doing more integration testing then unit ttestin.

So i wanted to find out how little you should copy from the web.config to make Sitecore test item now “FakeItem” extend more Sitecore functionality, for example Item.Children.

So i found by some investigation that the minimal configuration required to query the dataprovider is as follows

  <configSections>
    <section name="sitecore" type="Sitecore.Configuration.ConfigReader, Sitecore.Kernel" />
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, Sitecore.Logging" />
  </configSections>
  <sitecore database="SqlServer">
    <settings>
      <setting name="LicenseFile" value="D:\license.xml" />
    </settings>
  </sitecore>
  <log4net>
  </log4net>

Note that the path for the license file i absolute,

Now the problem is when asking for the ChildList through the Children Property you end up deep down in a provider instantiate by the ItemManager.  The default provider for some reason requires a valid licens. But with a valid license file now in place, what is next?

Why not replace the default Provider for the itemManager with a fake one, where we can control what to return for different calls to the Provider through the ItemManager.

<itemManager defaultProvider="default">
  <providers>
    <clear />
    <add name="default" type="Sitecore.Fakes.FakeItemProvider,Sitecore.Fakes" />
   </providers>
</itemManager>

and the complete configuration is now as follows

<configSections>
 <section name="sitecore" type="Sitecore.Configuration.ConfigReader, Sitecore.Kernel" />
 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, Sitecore.Logging" />
</configSections>
<sitecore database="SqlServer">
  <itemManager defaultProvider="default">
    <providers>
      <clear />
       <add name="default" type="Sitecore.Fakes.FakeItemProvider,Sitecore.Fakes" />
    </providers>
  </itemManager>
 <settings>
   <setting name="LicenseFile" value="D:\license.xml" />
 </settings>
</sitecore>
 <log4net>
 </log4net>

And my i present the new FakeItemProvider. And luckily Sitecore finally found good use of virtual methods.

public class FakeItemProvider : ItemProvider
{
 public override ChildList GetChildren(Item item, SecurityCheck securityCheck)
 {
    return new ChildList(item,((FakeItem)item).FakeChildren);
 }

 public override Item GetParent(Item item, SecurityCheck securityCheck)
 {
    return ((FakeItem) item).FakeParent;
 }
}

The fake itemprovider  depend on the FakeItem which I have extended a bit so it is possible to  add children and parents to an item. Off course this should be extended even more to support more Sitecore functionality.

 public class FakeItem : Item
 {
   public FakeItem(FieldList fieldList, string itemName = "FakeItem")
     : base(
    new ID(new Guid()),
    new ItemData(new ItemDefinition(new ID(new Guid()), itemName, new ID(new Guid()), new ID(new Guid())),
    Globalization.Language.Invariant, new Data.Version(1), fieldList),
    new Database("web"))
   {
     FakeChildren = new ItemList();
   }

  public void AddChild(Item child)
  {
   ((FakeItem) child).FakeParent = this;
    FakeChildren.Add(child);
  }

  public virtual Item FakeParent { get; set; }
  public virtual ItemList FakeChildren { get; set; }
 }

An example that shows the childList  and parent stub in action.

 public class FakeItemProviderTests
 {

   [Fact]
   public void FakeItem_AddMultipleChildren_ChildListShouldHaveAllChildren()
   {
    Item child = new FakeItem(new FieldList());
    FakeItem fake = new FakeItem(new FieldList());
    fake.AddChild(child);
    fake.AddChild(child);
    fake.AddChild(child);
    fake.AddChild(child);
    fake.AddChild(child);

    fake.Children.Should().HaveCount(5);
   }

  [Fact]
  public void FakeItem_AddChildToChildren_ShouldReturnChild()
  {
    Item child = new FakeItem(new FieldList());
    FakeItem fake = new FakeItem(new FieldList());
    fake.AddChild(child);

    fake.Children.First().ShouldBeEquivalentTo(child);
  }

  [Fact]
  public void FakeItem_AddChildToChildren_ChildShouldHaveParent()
  {
    Item child = new FakeItem(new FieldList());
    FakeItem fake = new FakeItem(new FieldList());
    fake.AddChild(child);

    fake.Children.First().Parent.ShouldBeEquivalentTo(fake);
  }

 [Fact]
 public void FakeItem_AddChildToChildren_ChildShouldHaveParentWithId()
 {
   Item child = new FakeItem(new FieldList());
   FakeItem fake = new FakeItem(new FieldList());
   fake.AddChild(child);

   fake.Children.First().ParentID.ShouldBeEquivalentTo(fake.ID);
 }
}

The code for this is free to download and can be found on GitHub Sitecore.Fakes.

Let me know what the next thing you like to get stubbed should be !

Typemock Isolator Review

07/06/2013 Leave a comment

Typemocks Isolator has been around for quite some time now, and I was given the opportunity to review version 7.4 of the product. Isolator is best known for the ability to test legacy code, i.e. code that with other mocking frameworks isn’t possible to mock or stub. Typemock ships the Isolator package with a lot more features than the ordinary mocking framework. Short list given below. I will consider each of these in this review.

Features of Typemock Isolator

  • Smart Runner
  • Coverage
  • Mock Interfaces
  • Mock Everything
  • Test Legacy Code
  • Test Code Autocompletion

Smart Runner
The smart runner allows for tests to be run when building your solution. At startup it examines all your current tests to get a baseline, and from that it should in for this session when rebuilding only run test relevant for the changes made. It sounds smart but In this context, I would rather use something like NCrunch. The good news is that NCrunch has support for Typemock Isolator. Maybe for larger application this would be a nice feature, especially if running the entire battery of tests takes more time than building your application.

Coverage
The coverage analyzer part is nice touch where you can hook up with your favorite test coverage analyzer for example DotCover or NCover. But, and this is a big but, for me with the test runner included with Typemock I simply can’t find a window or output which shows the entire test coverage for my application, not even for a single class. Maybe I’m missing something. But all I can see on each methods in each class. See images below.

tpcc
With that said I do like the information on coverage for methods where you easily can see which test covers the code. This is shown in the illustration below

tpmov2

Mock interfaces, Mock Everything and Test Legacy code
As with any mocking framework, e.g. Nsubstitute, Rhino, Moq, you can with the Isolator mock virtual methods, interfaces and abstract classes and methods. In addition, it is possible to mock statics-, private- methods and classes which cannot be mocked with standard mocking frameworks. As promised you can mock everything with Isolator.

I previously wrote a blog post where I stubbed out a lot of Sitecore functionality. You can read the blog post [Mocking Sitecore with Typemock Isolator Here].

Test Code Autocompletion
The intellisense for autocompletion for fakes is one of the features which quickly became one of my favorite things about Isolator. This feature really speeds up the process of writing tests.
As a standard this feature isn’t enabled to begin with. You will have to enable it under
Tools->Add-in manager
As illustrated here:

tpintel

Instead of writing Arrange part of a unit test, it automatically generates it for you using the shortcut “alt+7” .

Pros

  • Mock/Stub Everything
  • Test Code Autocompletion – Really liking this one.
  • Easy to use syntax

Cons

  • Missing Application/Class Test Coverage
  • Price

Conclusion
With the Isolator from Typemock you get much more than a standard mocking framework, you get a feature rich add-in for Visual Studio. For those only looking for an Isolation framework, this might be a bit too much. But if you are working in an organization with a lot of “Legacy Code” or trying to introduce unit testing or even TDD, I think the Isolator will offer you some really good assistance. It comes with a price tag but you also get a lot more than a standard isolation framework. For me working with Sitecore I need something like Isolator where you can mock/stub everything. But there are other alternatives out there for example Microsoft Fakes or JustMock, with Fakes coming free with Update 2 for Visual Studio, fakes syntax isn’t as intuitive as Typemocks Isolator..

If you are interested Typemock offers a lot of really good webinars. You can find a list of previous webinars [here]. Also if you follow them on twitter @Typemock you can be notified about upcoming webinars. With these webinars you can get a good introduction to unit testing and TDD, and how to introduce Testing into to your organization.

Categories: .Net, C#, Unit Testing Tags: , ,

Bubble Sort algorithm developed with TDD. Code Kata.

16/05/2011 2 comments

After I’ve been on a three day course with Uncle Bob in Copehangen, I got inspired by the code kata concept. And now want to do Kata from time to time to train coding.

I’ve wanted to start with something simple so I chose to do a sort algorithm. I was trying to make a video out of it, but got stuck with quicktime. Hoping to get it to work in the future. So for now you will have to settle with the testcases and code. I’m trying to use the guidelines from Clean Code so no comments will be in the code, functions and variable names should reveal their purpose.  How the code works should be visible from the Testcases.

Test cases.


package Sort;

import junit.framework.Assert;
import org.junit.Test;

import java.util.Arrays;

public class SorterTest {
  @Test
  public void SortEmptyList_ShouldReturnEmptyList() {
    Assert.assertTrue(Arrays.equals(new int[]{},
                        Sorter.Sort(new int[]{})));
 }

 @Test
 public void SortListWithOneElement_ShouldReturnSortedList() {
   Assert.assertTrue(Arrays.equals(new int[]{1},
                       Sorter.Sort(new int[]{1})));
 }

 @Test
 public void SortListWithTwoElementsInCorrectOrder_ShouldReturnSameList() {
   Assert.assertTrue(Arrays.equals(new int[]{1, 2},
                       Sorter.Sort(new int[]{1, 2})));
 }

 @Test
 public void SortListWithTwoElementsInReverseOrder_ShouldReturnSortedList() {
   Assert.assertTrue(Arrays.equals(new int[]{1, 2},
                       Sorter.Sort(new int[]{2, 1})));
 }

 @Test
 public void SortListWithSameTwoElementsr_ShouldReturnSortedList() {
   Assert.assertTrue(Arrays.equals(new int[]{2, 2},
                       Sorter.Sort(new int[]{2, 2})));
 }

 @Test
 public void SortListWithThreeElementsInCorrectOrder_ShouldReturnSortedList() {
   Assert.assertTrue(Arrays.equals(new int[]{1, 2, 3},
                       Sorter.Sort(new int[]{1, 2, 3})));
 }

 @Test
 public void SortListWithThreeElementsFirstTwoSwapped_ShouldReturnSortedList() {
   Assert.assertTrue(Arrays.equals(new int[]{1, 2, 3},
                       Sorter.Sort(new int[]{2, 1, 3})));
 }

 @Test
 public void SortListWithThreeElementslastTwoSwapped_ShouldReturnSortedList() {
   Assert.assertTrue(Arrays.equals(new int[]{1, 2, 3},
                       Sorter.Sort(new int[]{1, 3, 2})));
 }

 @Test
 public void SortListWithThreeElementslReverseOrder_ShouldReturnSortedList() {
   Assert.assertTrue(Arrays.equals(new int[]{1, 2, 3},
                       Sorter.Sort(new int[]{3, 2, 1})));
 }

 @Test
 public void SortListWithNElementaRandomOrder_ShouldReturnSortedList() {
   Assert.assertTrue(Arrays.equals(new int[]{1, 2, 3, 4, 5, 6, 6, 7, 8},
                       Sorter.Sort(new int[]{3, 2, 7, 6, 4, 8, 6, 1, 5})));
 }
}

And now to the refactored code.


package Sort;

public class Sorter {
  public static int[] Sort(int[] unSortedList) {
    if (unSortedList.length > 1)
      SortList(unSortedList);
    return unSortedList;
 }

 private static void SortList(int[] unSortedList) {
   int unsortedLength = unSortedList.length;
   while (unsortedLength > 0) {
     PlacedLargestElementAtEndOfList(unSortedList);
     unsortedLength--;
   }
 }

 private static void PlacedLargestElementAtEndOfList(int[] unSortedList) {
   for (int j = 0; j < i.length - 1; j++)
     SortElements(unSortedList, j);
 }

 private static void SortElements(int[] unSortedList, int j) {
   if (unSortedList[j] > unSortedList[j + 1])
     SwapElements(unSortedList, j);
 }

 private static void SwapElements(int[] unSortedList, int j) {
   int backupelement = unSortedList[j];
   unSortedList[j] = unSortedList[j + 1];
   unSortedList[j + 1] = backupelement;
 }
}
Categories: Java Tags: , ,