Sunday, 24 May 2009

NUnit and NMock

Whist working on a piece of course work for uni I started using NMock as part of some unit tests written using nunit. Having mainly used MSTests for unit tests at work I decided to use nunit as everyone has said that they are very similar. I'm extremely impressed with the potential power that NMock has given me during testing. For the assignment I wrote a small spider application that crawly a site and stores all the link. Using NMock it allowed me to test the structure of the site without requiring internet access. During this assignment I also tried to use the test driven development approach, opposed to my normal sit down and hack away. Not only were there less bugs at the end, the overall quality of my code was noticeable higher. This was largely due to the fact that I had tests already created for what it was meant to do, which required me to put more effort into the implementation. Hopefully I'll keep this style of programming up, and not just forget it as soon as I get back to work.


Here's a sample nunit test that uses nmock. The nmock object mocks the calls that request specific urls and loads the data for local files.

[Test()]
public void MockLinkFinderTest()
{
IMock mockWebClient = new DynamicMock(typeof(IWebClient));
mockWebClient.ExpectAndReturn("GetPage",File.ReadAllText("HTML/1.htm"),new object[]{"http://domain.example/1.htm"});
mockWebClient.ExpectAndReturn("GetPage",File.ReadAllText("HTML/2.htm"),new object[]{"http://domain.example/2.htm"});
mockWebClient.ExpectAndReturn("GetPage",File.ReadAllText("HTML/3.htm"),new object[]{"http://domain.example/3.htm"});

string domain = "domain.example";
string url = "http://domain.example/1.htm";

LinkFinder linkFinder = new LinkFinder();
LinkItemCollection linkCollection = linkFinder.Find(url,domain,(IWebClient)mockWebClient.MockInstance);

int expected = 3;
Assert.AreEqual(expected,linkCollection.Count);
}

No comments:

Post a Comment