How to set EntityCollection property of service response for unit testing purposes [CRM]

When unit testing CRM C# codes, you may find that you need to mock the response of calls to CRM’s Organisation service. A number of response classes in the SDK contain an EntityCollection property. This property however is null and is read-only, which means you cannot populate it with mock entries – or at least it seems that way.

This will not work:

var mockResponse = new InstantiateTemplateRequest();

//This won't compile as EntityCollection property does not have a setter
mockResponse.EntityCollection = new EntityCollection();

Neither will this:

var mockResponse = new InstantiateTemplateRequest();

//This will give you a run-time exception as EntityCollection property is null.
mockResponse.EntityCollection.Add(new Entity());   

Behind the scene, the EntityCollection property is actually a facade for reading a key from the Results property. The Results property is defined on the base class of all response classes.

You therefore can set and populate the EntityCollection property as follow:

//The mock response
var response = new InstantiateTemplateResponse();
response.Results["EntityCollection"] = new EntityCollection(new List<Entity> { new Entity() });

//response.EntityCollection will now contain one mock entity that we have just configured above.
Advertisements

About Bernado

Based in Australia, I am a freelance SharePoint and Dynamics CRM developer. I love developing innovative solutions that address business and everyday problems. Feel free to contact me if you think I can help you with your SharePoint or CRM implementation.
This entry was posted in CRM, Unit Test. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s