Sharepoint DDD / TDD Code Testing Tip

In this post i would like to demonstrate a small tip in writing SharePoint code, which can make testing a bit easy.

Now before going into further details lets talk about 2 concepts DDD and Unit Test Vs Integration Test.

#1. DDD & TDD : Domain Driven Development  targets at unrelenting Domain layer from technology, thus making it flexible to be accessed by any technology for re-usability.

On the other hand TDD targets at implementing the functionality based on scenarios. For example, lets consider Agile implementation. Each sprint will target a couple of scenarios, which may not comprises of complete functionality. So, we will write the test cases for those scenarios and will write the code against to the test cases until they are success.

In both the cases, the main idea is separation of concerns and increasing the testability of the code.

#2. Unit Test is a test that will be executed in isolation, means no dependency on any other factor. In SharePoint , the unit test should be executed even without Sharepoint dlls, and Sites, and any other factor.
We have several frameworks like Moles, TypeMock which will give you ability to mock complete SP Object model thus execute your code in isolation.

On the other hand Integration testing is running the code in coordination with various layers that actually perform tasks on the site.

So i have created a small SharePoint sample application page. It will fetch all the list names and populate in listbox.

So, i created it following DDD pattern. So it will have Domain Layer, Infrastructure, and UI layer.

So, the "ListRepository" class in infrastructure  will deal with SP part of dealing with sites and lists. Populating the data to domain objects and sending back to UI.

The following code will give you clear idea what i am doing.

Application Page Code:

ListRepository code:
So now coming to testing this method, i created a test method, which checks the count of lists and will pass if if result is not null.
Lets see the out come.
The test method failed with an exception

"Test method xxxxx threw exception:
System.NullReferenceException: Object reference not set to an instance of an object."

Its not that my code is wrong. The test method cannot load SharePoint context by itself while execution.
So here comes my tip to just change your infrastructure code a bit to make it flexible for testing.

Updated ListRepository code:
Now the Test method code changes to accommodate weburl.
 The result is :

Now we were able to test code in all the layers of the project.

No comments:

Post a Comment