Thursday, July 24, 2008

Automated Tests in my life - part 6

What is Mocking?

Sometimes we want to test a method, which is dependent on other methods
results or some complecated data. In these situations in order to write a little unit test, we need to make lots of initializations.
For example if we take a code:

public string GetProcessedBatchOfCAMLCommands()
{
string batch = string.Empty;

// initialize the new instance of SP Site
using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.OpenWeb())
{
SPListItemCollection UnprocessedSPListItemsCollection = GetListAndQueryItems(web);
string listGuid = web.Lists["Processed Documents"].ID.ToString();
batch = GetFormattedCAMLBatchCommand(UnprocessedSPListItemsCollection,listGuid);
string batchReturn = web.ProcessBatchData(batch);
}
}
return batch;
}

Lets look at the GetFormattedCAMLBatchCommand method. Let's say we want to test it.
The method is dependent on SPSite, SPWeb and etc... There is chain of dependencies.
So how can we test GetFormattedCAMLBatchCommand without involving these dependencies?
We should isolate the method from other dependencies.
Ok, so we can mock other dependencies and send to GetFormattedCAMLBatchCommand "faked" objects. We will be able to unit test it.
This is a principle, I will try to explain you this by simple example

No comments: